Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

在 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:

shared
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]:

Counter
<button onclick={() => {}}>
	clicks: {$count}
</button>

最后,添加事件处理程序。因为这是一个可写存储,我们可以使用其 setupdate 方法以编程方式更新值...

¥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:

Counter
<button onclick={() => $count += 1}>
	clicks: {$count}
</button>
1
2
3
4
5
6
7
8
<script>
	import Counter from './Counter.svelte';
</script>
 
<Counter />
<Counter />
<Counter />