持久化
自定义持久化插件
ts
store.use(persistPlugin)
function persistPlugin(context: PiniaPluginContext) {
const key = context.store.$id
const isPersist = context.store.$options.persist
if (isPersist) {
window.addEventListener('beforeunload', () => {
localStorage.setItem(key, JSON.stringify(context.store.$state))
})
const isSaved = localStorage.getItem(key)
if (isSaved) {
context.store.$patch(JSON.parse(isSaved))
}
}
}