pinia插件的方式,实现持久化存储
- 创建插件:
persistencePlugin.ts
import type { PiniaPluginContext } from 'pinia'
interface PersistenceItem {
name: string,
stateList: string[]
}
const persistenceSet = (key: string, value: string) => {
localStorage.setItem(key, value)
}
const persistenceGet = (key: string) => {
return localStorage.getItem(key) ? localStorage.getItem(key) : ''
}
export function persistencePlugin(persistenceList: PersistenceItem[]) {
return (context: PiniaPluginContext) => {
persistenceList.forEach(item => {
if (context.store.$id === item.name && item.stateList.length > 0) {
item.stateList.forEach(key => {
context.store.$state[key] = persistenceGet(key)
})
context.store.$subscribe((mutation) => {
if (item.stateList.includes((<any>mutation.events).key)) {
const value = (<any>mutation.events).newValue
const valueType = typeof value
persistenceSet((<any>mutation.events).key, valueType === 'string' ? value : JSON.stringify(value))
}
})
}
})
}
}
main.ts 中使用插件
import { persistencePlugin } from './stores/plugins/persistencePlugin'
const app = createApp(App)
const pinia = createPinia()
pinia.use(persistencePlugin([{
name: 'user',
stateList: ['userid']
}]))