实现思路
- 多层嵌套状态:使用
writable
来创建基础的可写状态,通过对象嵌套来构建多层结构。
- 状态衍生计算:利用
derived
基于已有的 writable
状态计算衍生状态。
- 用户角色权限:定义不同用户角色及其对应的读写权限逻辑,在状态读写操作时进行权限检查。
关键代码片段
<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>