更新 Svelte 可写数组存储的正确方法是什么?
What is the correct way for updating a Svelte writable array store?
更新 $orderItems = writable([])
Svelte 可写数组存储的正确方法是什么(或者如果两者都正确则有区别)?我们假设 result
是我想在 $orderItems
结束时推送的新项目。
orderItems.update(items => ([...items, result]))
或
$orderItems = [...$orderItems, result]
两者都正确,另一种选择是
$orderItems.push(result)
$orderItems = $orderItems
和
orderItems.update(items => {
items.push(result)
return items
})
区别在于$
语法只能在组件内部使用,所以.svelte
文件。来自 the docs
Any time you have a reference to a store, you can access its value inside a component by prefixing it with the $ character. This causes Svelte to declare the prefixed variable, subscribe to the store at component initialization and unsubscribe when appropriate.
如果您想从 .js
文件修改商店,只能通过 .set() / .update()
完成
更新 $orderItems = writable([])
Svelte 可写数组存储的正确方法是什么(或者如果两者都正确则有区别)?我们假设 result
是我想在 $orderItems
结束时推送的新项目。
orderItems.update(items => ([...items, result]))
或
$orderItems = [...$orderItems, result]
两者都正确,另一种选择是
$orderItems.push(result)
$orderItems = $orderItems
和
orderItems.update(items => {
items.push(result)
return items
})
区别在于$
语法只能在组件内部使用,所以.svelte
文件。来自 the docs
Any time you have a reference to a store, you can access its value inside a component by prefixing it with the $ character. This causes Svelte to declare the prefixed variable, subscribe to the store at component initialization and unsubscribe when appropriate.
如果您想从 .js
文件修改商店,只能通过 .set() / .update()