MST
星途 面试题库

面试题:Svelte状态管理:writable与derived的深度集成与定制

在一个大型Svelte项目中,需要将writable和derived深度集成以实现复杂的状态管理逻辑。要求创建一个具有多层嵌套状态且部分状态依赖其他状态衍生计算的场景,同时,根据不同用户角色定制状态的读写权限。请详细描述实现思路,并给出关键代码片段。
23.1万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 多层嵌套状态:使用 writable 来创建基础的可写状态,通过对象嵌套来构建多层结构。
  2. 状态衍生计算:利用 derived 基于已有的 writable 状态计算衍生状态。
  3. 用户角色权限:定义不同用户角色及其对应的读写权限逻辑,在状态读写操作时进行权限检查。

关键代码片段

<script>
    import { writable, derived } from'svelte/store';

    // 多层嵌套的可写状态
    const userProfile = writable({
        basicInfo: {
            name: 'John Doe',
            age: 30
        },
        address: {
            street: '123 Main St',
            city: 'Anytown'
        }
    });

    // 衍生状态,例如计算全名
    const fullName = derived(userProfile, ($profile) => {
        return `${$profile.basicInfo.name}`;
    });

    // 模拟用户角色
    const userRole = writable('admin');

    // 读取状态时的权限检查
    function readProfile() {
        if ($userRole === 'admin' || $userRole === 'user') {
            userProfile.subscribe((profile) => {
                console.log('Read profile:', profile);
            });
        } else {
            console.log('No read permission');
        }
    }

    // 写入状态时的权限检查
    function updateProfile(newProfile) {
        if ($userRole === 'admin') {
            userProfile.set(newProfile);
        } else {
            console.log('No write permission');
        }
    }
</script>

<button on:click={readProfile}>Read Profile</button>
<button on:click={() => updateProfile({ basicInfo: { name: 'Jane Smith', age: 25 }, address: { street: '456 Elm St', city: 'Othertown' } })}>Update Profile</button>