面试题答案
一键面试1. 创建 Svelte 自定义 store 管理主题状态
// themeStore.js
import { writable } from'svelte/store';
// 创建一个可写的 store 来管理主题
const themeStore = writable('light');
// 定义切换主题的函数
function setTheme(theme) {
themeStore.set(theme);
}
export { themeStore, setTheme };
2. 确保不同模块间主题状态的一致性
在每个需要使用主题的模块中,导入 themeStore
。
// SomeComponent.svelte
<script>
import { themeStore } from './themeStore.js';
let currentTheme;
themeStore.subscribe((value) => {
currentTheme = value;
});
</script>
{#if currentTheme === 'light'}
<p>当前主题为浅色</p>
{:else}
<p>当前主题为深色</p>
{/if}
3. 处理主题切换时的副作用(如动画过渡)
可以利用 Svelte 的 transition
功能。
// App.svelte
<script>
import { themeStore, setTheme } from './themeStore.js';
import { fade } from'svelte/transition';
let currentTheme;
themeStore.subscribe((value) => {
currentTheme = value;
});
</script>
<button on:click={() => setTheme(currentTheme === 'light'? 'dark' : 'light')}>切换主题</button>
<div transition:fade>
{#if currentTheme === 'light'}
<p style="background-color: white; color: black;">浅色主题内容</p>
{:else}
<p style="background-color: black; color: white;">深色主题内容</p>
{/if}
</div>
关键逻辑总结
- 主题状态管理:通过 Svelte 的
writable
store 来存储和管理主题状态,提供一个setTheme
函数方便其他模块切换主题。 - 状态一致性:各个模块通过订阅
themeStore
来获取主题状态的更新,确保所有模块展示的主题一致。 - 副作用处理:利用 Svelte 的
transition
功能为主题切换添加动画过渡效果,增强用户体验。