- 基本步骤:
- 导入
svelte/store
中的 writable
函数(用于创建可写存储)。
- 使用
writable
函数创建一个存储对象,该对象包含 subscribe
、set
和 update
方法。subscribe
用于订阅存储值的变化,set
用于直接设置新值,update
用于基于当前值计算并设置新值。
- 在不同组件中导入该存储对象,通过
subscribe
订阅变化,通过 set
或 update
修改状态。
- 示例代码:
import { writable } from'svelte/store';
export const sharedStore = writable(0);
- 修改状态的组件
ComponentA.svelte
:
<script>
import { sharedStore } from './store.js';
function increment() {
sharedStore.update(n => n + 1);
}
</script>
<button on:click={increment}>Increment</button>
- 响应变化的组件
ComponentB.svelte
:
<script>
import { sharedStore } from './store.js';
let value;
const unsubscribe = sharedStore.subscribe(newValue => {
value = newValue;
});
$: console.log('Value changed:', value);
// 确保在组件销毁时取消订阅
onDestroy(() => {
unsubscribe();
});
</script>
<p>The value is: {value}</p>