Svelte Motion弹簧数组使用报错:无subscribe方法的解决方法
解决Svelte Motion Spring数组的订阅错误
错误原因
Svelte的$语法仅支持直接订阅单个store变量,没法直接作用于数组或者数组索引表达式(比如coords[j])。你尝试用{$coords[j].x}时,Svelte会误把coords当成store,但它只是包含多个Spring store的普通数组,所以触发了"coords is not a store"的错误。
解决方案(无需自定义store)
1. 循环遍历的时候直接用单个Spring元素
如果是用{#each}遍历数组,直接把每个Spring实例赋值给循环变量,再给变量加$订阅:
<script> import { spring } from 'svelte-motion'; // 创建Spring数组 const coords = [ spring({ x: 0, y: 0 }), spring({ x: 100, y: 100 }), // 可以加更多Spring实例 ]; </script> {#each coords as coord} <div style="position: absolute; left: {$coord.x}px; top: {$coord.y}px"> 可移动元素 </div> {/each}
2. 固定索引访问:先把Spring元素存到变量里
如果要通过固定索引(比如coords[1])访问,先把目标Spring实例赋值给单独的变量,再用$订阅这个变量:
<script> import { spring } from 'svelte-motion'; const coords = [ spring({ x: 0, y: 0 }), spring({ x: 200, y: 200 }) ]; // 把要用到的Spring实例提取出来 const targetCoord = coords[1]; </script> <div style="position: absolute; left: {$targetCoord.x}px; top: {$targetCoord.y}px"> 指定索引的元素 </div>
3. 内联用临时变量处理
如果不想额外声明变量,也可以在模板里用{#set}声明临时变量存储单个Spring实例:
{#each coords as _, j} {#set coord = coords[j]} <div style="left: {$coord.x}px; top: {$coord.y}px"></div> {/set} {/each}
以上方法都能正确订阅每个Spring store的数值,而且完全不需要创建自定义store。
内容的提问来源于stack exchange,提问作者Hello-World
相关产品推荐
相关产品推荐

