正文
下面代码中手动订阅与取消订阅的代码其实非常冗余,Svelte 提供了自动订阅的功能,可以自动为我们做订阅和取消订阅的操作。
<script> import { writable } from 'svelte/store' import {onDestroy} from 'svelte' const count = writable(0) let countVal; // 手动订阅 const unsubscribe = count.subscribe((val) => { countVal = val; }); // 组件卸载时手动取消订阅 onDestroy(unsubscribe) // ... </script>
用法也很简单,就是在引入的目标 store-state 变量前面加一个 $
符号即可,如下所示:
<script> // 创建仓库 import { writable } from 'svelte/store' // 声明一个可写的 state 并指定初始值 const count = writable(0) // 增加 const increment = () => { // 更新 store-state count.update((n) => n + 1); }; // 减少 const decrement = () => { // 更新 store-state count.update((n) => n - 1); }; // 重置 const reset = () => { // 重置 store-state count.set(0); }; </script> <h1>{$count}</h1> <button on:click={increment}>+</button> <button on:click={decrement}>-</button> <button on:click={reset}>reset</button>