MST

星途 面试题库

面试题:Svelte 自定义 store 中如何实现一个简单的计数 store

请用 Svelte 编写代码实现一个自定义 store,该 store 用于计数,具备增加计数、减少计数的功能,并说明这种自定义 store 如何在组件中使用。
37.1万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试

1. 编写自定义 Svelte store

// countStore.js
import { writable } from'svelte/store';

function createCountStore() {
    const { subscribe, set, update } = writable(0);

    return {
        subscribe,
        increment: () => update(n => n + 1),
        decrement: () => update(n => n - 1)
    };
}

export const countStore = createCountStore();

2. 在组件中使用自定义 store

// CountComponent.svelte
<script>
    import { countStore } from './countStore.js';
    let count;
    const unsubscribe = countStore.subscribe(value => {
        count = value;
    });

    const incrementCount = () => {
        countStore.increment();
    };

    const decrementCount = () => {
        countStore.decrement();
    };

    // 组件销毁时取消订阅
    $: onDestroy(() => {
        unsubscribe();
    });
</script>

<div>
    <p>Count: {count}</p>
    <button on:click={incrementCount}>Increment</button>
    <button on:click={decrementCount}>Decrement</button>
</div>

解释:

  1. 自定义 store:通过 writable 创建一个可写的 store,初始值为 0 。然后返回一个对象,对象中包含 subscribe 方法用于订阅 store 的变化,以及 incrementdecrement 方法分别用于增加和减少计数。
  2. 组件中使用:在组件中导入自定义 store,通过 subscribe 方法订阅 store 的变化并更新组件中的变量 count 。定义 incrementCountdecrementCount 方法来调用 store 中的 incrementdecrement 方法实现计数的增加和减少 。最后在组件销毁时,通过 onDestroy 取消订阅,防止内存泄漏。