Svelte:使用基于模块上下文变量的反应式语句

Jam*_*bet 4 svelte svelte-component

我想使用在组件的多个实例之间共享的代码来启动每个组件内的代码。

我尝试使用反应式语句来做到这一点:

<script context="module">
    let what = 0;
</script>

<script>
    export let number;
    $: if (what === number) [...]
</script>
Run Code Online (Sandbox Code Playgroud)

但对 的更改what不会触发该反应语句的重新运行。

为什么这个 REPL 不起作用,我该如何修复它?

https://svelte.dev/repl/38b94490982f4f3c80644fd364b50723?version=3.16.0

Jam*_*bet 9

更改what为 awritable似乎可以解决问题:

<script context="module">
    import { writable } from 'svelte/store';
    const what = writable(0);
</script>

<script>
    export let number;
    $: if ($what === number) [...]
</script>
Run Code Online (Sandbox Code Playgroud)

https://svelte.dev/repl/f667f3eb6b7d453da1473d5e26268814?version=3.16.0

  • 在 `context="module"` 脚本中使用存储确实是推荐的方法。[“‘module’脚本中定义的变量不是反应性的——即使变量本身会更新,重新分配它们也不会触发重新渲染。对于多个组件之间共享的值,请考虑使用‘store’。”](https://svelte .dev/docs#script_context_module) (2认同)