在前面的练习中,我们使用符文在组件内部添加反应性。但我们也可以在组件外部使用符文,例如共享一些全局状态。
¥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 so nothing happens when you click the buttons. Wrap the object in $state(...):
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:
<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声明被重新赋值(而不仅仅是修改),则你无法从模块中导出该声明,因为导入器无法获知它。
<script>
import Counter from './Counter.svelte';
</script>
<Counter />
<Counter />
<Counter />