MST

星途 面试题库

面试题:Svelte 中如何自定义一个用于主题切换的 store

请描述在 Svelte 中自定义一个 store 实现主题切换功能的基本步骤,包括如何初始化 store、如何在组件中使用该 store 以及如何更新主题。
13.0万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试
  1. 初始化 store
    • 在 Svelte 中,使用 writable 函数来创建一个可写的 store。例如,假设我们有两种主题 lightdark,我们可以这样初始化主题 store:
    import { writable } from'svelte/store';
    
    const themeStore = writable('light');
    export default themeStore;
    
  2. 在组件中使用该 store
    • 在组件中,通过 $ 前缀来访问 store 的值。例如:
    <script>
        import themeStore from './themeStore.js';
    </script>
    
    <div class={$themeStore === 'light'? 'light - theme' : 'dark - theme'}>
        <!-- 组件内容 -->
    </div>
    
    • 还可以使用 subscribe 方法来订阅 store 的变化,当主题变化时执行一些副作用操作:
    <script>
        import themeStore from './themeStore.js';
        let theme;
        const unsubscribe = themeStore.subscribe((value) => {
            theme = value;
            // 在这里可以执行如更新文档标题等副作用操作
        });
        // 在组件销毁时取消订阅
        $: onDestroy(() => {
            unsubscribe();
        });
    </script>
    
  3. 更新主题
    • 直接通过赋值来更新 store 的值。例如,在一个切换主题的按钮点击事件中:
    <script>
        import themeStore from './themeStore.js';
        const toggleTheme = () => {
            $themeStore = $themeStore === 'light'? 'dark' : 'light';
        };
    </script>
    
    <button on:click={toggleTheme}>切换主题</button>
    
    • 也可以使用 update 方法来更新 store,这种方式更适用于需要基于当前值进行计算的情况:
    <script>
        import themeStore from './themeStore.js';
        const toggleTheme = () => {
            themeStore.update((currentTheme) => currentTheme === 'light'? 'dark' : 'light');
        };
    </script>
    
    <button on:click={toggleTheme}>切换主题</button>