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

在前面的练习中,我们使用符文在组件内部添加反应性。但我们也可以在组件外部使用符文,例如共享一些全局状态。

¥In the preceding exercises, we used runes to add reactivity inside components. But we can also use runes outside components, for example to share some global state.

本练习中的 <Counter> 组件都是从 shared.js 导入 counter 对象。但它是一个普通对象,因此单击按钮时不会发生任何事情。将对象封装在 $state(...) 中:

¥The <Counter> components in this exercise are all importing the counter object from shared.js. But it’s a normal object, and as such nothing happens when you click the buttons. Wrap the object in $state(...):

shared
export const counter = $state({
	count: 0
});

这会导致错误,因为你不能在普通 .js 文件中使用符文,只能在 .svelte.js 文件中使用。让我们修复它 — 将文件重命名为 shared.svelte.js

¥This causes an error, because you can’t use runes in normal .js files, only .svelte.js files. Let’s fix that — rename the file to shared.svelte.js.

然后,更新 Counter.svelte 中的导入声明:

¥Then, update the import declaration in Counter.svelte:

Counter
<script>
	import { counter } from './shared.svelte.js';
</script>
<script lang="ts">
	import { counter } from './shared.svelte.js';
</script>

现在,当你单击任何按钮时,所有三个都会同时更新。

¥Now, when you click any button, all three update simultaneously.

如果声明被重新分配(而不仅仅是修改),则你无法从模块中导出 $state 声明,因为导入器无法知道它。

¥[!NOTE] You cannot export a $state declaration from a module if the declaration is reassigned (rather than just mutated), because the importers would have no way to know about it.

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