在 Svelte 5 中引入符文之前,存储是处理组件外部反应状态的惯用方式。情况不再如此,但在使用 Svelte(目前包括在 SvelteKit 中)时你仍会遇到存储,因此值得了解如何使用它们。
¥Prior to the introduction of runes in Svelte 5, stores were the idiomatic way to handle reactive state outside components. That’s no longer the case, but you’ll still encounter stores when using Svelte (including in SvelteKit, for now), so it’s worth knowing how to use them.
我们不会介绍如何创建你自己的自定义存储 — 为此,查阅文档。
¥[!NOTE] We won’t cover how to create your own custom stores — for that, consult the documentation.
让我们重新审视 通用反应性 练习中的示例,但这次使用存储实现共享状态。
¥Let’s revisit the example from the universal reactivity exercise, but this time implement the shared state using a store.
在 shared.js
中,我们目前正在导出 count
,这是一个数字。将其转换为可写存储:
¥In shared.js
we’re currently exporting count
, which is a number. Turn it into a writable store:
import { writable } from 'svelte/store';
export const count = writable(0);
要引用存储的值,我们在其前面加上 $
符号。在 Counter.svelte
中,更新 <button>
中的文本,使其不再显示 [object Object]
:
¥To reference the value of the store, we prefix it with a $
symbol. In Counter.svelte
, update the text inside the <button>
so that it no longer says [object Object]
:
<button onclick={() => {}}>
clicks: {$count}
</button>
最后,添加事件处理程序。因为这是一个可写存储,我们可以使用其 set
或 update
方法以编程方式更新值...
¥Finally, add the event handler. Because this is a writable store, we can update the value programmatically using its set
or update
method...
count.update((n) => n + 1);
...但由于我们在组件中,我们可以继续使用 $
前缀:
¥...but since we’re in a component we can continue using the $
prefix:
<button onclick={() => $count += 1}>
clicks: {$count}
</button>
<script>
import Counter from './Counter.svelte';
</script>
<Counter />
<Counter />
<Counter />