面试题答案
一键面试- 初始化 store:
- 在 Svelte 中,使用
writable
函数来创建一个可写的 store。例如,假设我们有两种主题light
和dark
,我们可以这样初始化主题 store:
import { writable } from'svelte/store'; const themeStore = writable('light'); export default themeStore;
- 在 Svelte 中,使用
- 在组件中使用该 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>
- 在组件中,通过
- 更新主题:
- 直接通过赋值来更新 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>