再我使用网上各种插件都失效的情况下
手写一个本地存储插件,做到Pinia本地持久化
store/plugin.ts
import type{ PiniaPluginContext } from 'pinia';
import {toRaw} from 'vue';
type Options = { key?:string }
const KEY = 'pinia';
const setStorage = (key:string,value:any) => {
localStorage.setItem(key,JSON.stringify(value))
}
const getStorage = (key:string) => {
return localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key) as string) : {}
}
const piniaPlugin = (options:Options) => {
return (context:PiniaPluginContext) => {
const {store} = context;
const data = getStorage(`${options?.key ?? KEY}-${store.$id}`);
store.$subscribe(()=>{
setStorage(`${options?.key ?? KEY}-${store.$id}`,toRaw(store.$state))
});
console.log(store,'store');
return {...data}
}
}
export default piniaPlugin;
然后引入main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import piniaPlugin from './store/plugin'
import App from './App.vue'
const store = createPinia()
store.use(piniaPlugin({
key: "store"
}))
const app = createApp(App)
app.use(store)