MST

星途 面试题库

面试题:Svelte 自定义 store 主题切换在复杂应用架构下的设计与实现

假设你正在开发一个大型的 Svelte 应用,具有多个独立的模块且每个模块都可能需要访问和切换主题。请设计一个完整的基于 Svelte 自定义 store 的主题切换架构,说明如何管理不同模块间主题状态的一致性,如何处理主题切换时可能产生的副作用(如动画过渡等),并给出核心的代码框架和关键逻辑。
23.2万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试

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>

关键逻辑总结

  1. 主题状态管理:通过 Svelte 的 writable store 来存储和管理主题状态,提供一个 setTheme 函数方便其他模块切换主题。
  2. 状态一致性:各个模块通过订阅 themeStore 来获取主题状态的更新,确保所有模块展示的主题一致。
  3. 副作用处理:利用 Svelte 的 transition 功能为主题切换添加动画过渡效果,增强用户体验。