MST

星途 面试题库

面试题:Svelte 中如何通过 store 实现简单的组件间状态共享

请阐述在 Svelte 里,使用 `svelte/store` 来创建一个可在不同组件间共享状态的基本步骤,并给出一个简单示例代码,说明如何在一个组件中修改状态,另一个组件响应此变化。
31.6万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试
  1. 基本步骤
    • 导入 svelte/store 中的 writable 函数(用于创建可写存储)。
    • 使用 writable 函数创建一个存储对象,该对象包含 subscribesetupdate 方法。subscribe 用于订阅存储值的变化,set 用于直接设置新值,update 用于基于当前值计算并设置新值。
    • 在不同组件中导入该存储对象,通过 subscribe 订阅变化,通过 setupdate 修改状态。
  2. 示例代码
    • 创建一个共享存储 store.js
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>