Svelte如何为derived派生状态传入参数并保持响应性?
你定义的derivedValue本质是store工厂函数,调用它返回的就是标准可订阅的Svelte store,可直接配合$语法使用,两种常用实现方案如下:
方案1:直接调用工厂函数生成store
这种方式最简洁,适合索引固定、或者不需要复用同索引store的场景。
store.js 代码
import { derived, writable } from 'svelte/store'; export const myArray = writable([6, 7, 8, 9, 10]); // 导出store工厂函数,传入索引返回对应派生store export const getDerivedByIndex = index => derived(myArray, value => value[index]);
组件内使用示例
<script> import { myArray, getDerivedByIndex } from './store'; // 调用工厂函数拿到对应索引的store,可直接用$订阅 const derivedValue3 = getDerivedByIndex(3); const derivedValue1 = getDerivedByIndex(1); </script> <h1>{$myArray}</h1> <h1>索引3的值:{$derivedValue3}</h1> <h1>索引1的值:{$derivedValue1}</h1>
方案2:增加缓存层优化复用
如果同一个索引的派生store会被多处使用,可增加缓存逻辑避免重复创建实例,减少订阅开销:
带缓存的store.js 代码
import { derived, writable } from 'svelte/store'; export const myArray = writable([6, 7, 8, 9, 10]); // 缓存已创建的索引store const indexStoreCache = new Map(); export const getDerivedByIndex = index => { // 已缓存直接返回 if (indexStoreCache.has(index)) return indexStoreCache.get(index); // 未缓存则创建并存入缓存 const store = derived(myArray, value => value[index]); indexStoreCache.set(index, store); return store; };
方案3:动态切换索引场景的实现
如果需要在运行时动态切换要订阅的索引,可额外声明一个存索引的writable store,同时依赖两个store派生:
代码示例
// store.js import { derived, writable } from 'svelte/store'; export const myArray = writable([6, 7, 8, 9, 10]); // 存当前选中的索引 export const selectedIndex = writable(3); // 同时依赖数组和索引派生,索引变化也会自动更新值 export const currentDerivedValue = derived( [myArray, selectedIndex], ([arr, idx]) => arr[idx] );
组件内动态切换示例
<script> import { selectedIndex, currentDerivedValue } from './store'; </script> <h1>当前索引对应值:{$currentDerivedValue}</h1> <button on:click={() => $selectedIndex = 1}>切换到索引1</button> <button on:click={() => $selectedIndex = 4}>切换到索引4</button>
内容的提问来源于stack exchange,提问作者gurumaxi
相关产品推荐
相关产品推荐

