Logo
Section 1 / 3

创建应用程序的初始状态

学习如何使用本地存储 API 在 Svelte 中设置应用的初始状态。

导入

创建应用程序的初始状态

学习如何使用本地存储 API 在 Svelte 中设置应用的初始状态。

1import { writable, get } from 'svelte/store'; 2 3const localState = localStorage.getItem('state'); 4const initialState = { 5 students: [] 6}; 7 8if (!localState) { 9 localStorage.setItem('state', JSON.stringify(initialState)); 10} 11 12const appState = localState ? JSON.parse(localState) : initialState; 13 14export const state = writable(appState); 15export const update = callback => { 16 const updatedState = callback(get(state)); 17 18 state.update(() => updatedState); 19 localStorage.setItem('state', JSON.stringify(updatedState)); 20};

结论

集成 Tailwind