Skip to main content
Svelte基础
介绍
响应
属性Props
逻辑表达式
事件
绑定
Classes和样式
动作Actions
转场
Svelte高阶
响应式进阶
内容复用
动画
高级绑定
高级转场
上下文API
特殊元素
脚本模块
接下来
SvelteKit基础
介绍
路由
加载数据
Headers和cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

在Svelte 5引入符文(rune)以前,在组件外使用响应式状态通常使用store实现。现在已经不这么用了,但在使用Svelte的时候偶尔还会见到store(比如使用SvelteKit), 那就认识下吧.

我们就不涉及自定义store了,如果想了解相关内容可以看相关秘笈.

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. We won’t cover how to create your own custom stores — for that, consult the documentation.

我们依然使用全局响应的练习,但这次我们使用store创建一个共享状态。 在shared.js里我们先前导出了数字count。这次把它转换成可写入(writable)store:

Let’s revisit the example from the universal reactivity exercise, but this time implement the shared state using a store. 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);

可以通过在变量名称前添加$使用store. 修改下<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>

最后添加事件处理器,因为这是一个可写入store, 所以我们可以通过编程的方法调用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>

Edit this page on GitHub

1
2
3
4
5
6
7
8
<script>
	import Counter from './Counter.svelte';
</script>
 
<Counter />
<Counter />
<Counter />