Pinia和Vuex都有刷新页面状态会丢失的问题
Pinia通过自定义一个pinia插件实现数据持久化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
import { createApp, toRaw } from 'vue' import { createPinia, PiniaPluginContext } from 'pinia' const store = createPinia()
const __storageKey = 'pinia'
type Options = { key: string }
const setStorage = (key: string, value: any) => { localStorage.setItem(key, JSON.stringify(value)) }
const getStorage = (key: string) => { const value = localStorage.getItem(key) return value ? JSON.parse(value) : null }
const PiniaPlugin = (options: Options) => { return (content: PiniaPluginContext) => { const { store } = content const data = getStorage(`${options?.key ?? __storageKey}-${store.$id}`) if (data) { return { ...data } } else { store.$subscribe(() => { setStorage(`${options?.key ?? __storageKey}-${store.$id}`, toRaw(store.$state)) }) } } }
store.use(PiniaPlugin({ key: 'pinia' }))
|