七、Vue3使用Pinia刷新页面状态丢失解决方案

使用pinia-plugin-storage插件

npm i pinia-plugin-storage

或者手写一个本地存储插件,做到Pinia本地持久化

src/plugin/piniaPlugin.ts

import { type PiniaPluginContext } from 'pinia';
import {toRaw} from 'vue';
type Options = { key?:string }
const __pinia_key__:string = '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 ?? __pinia_key__}-${store.$id}`);
        store.$subscribe(()=>{ // 监听store变化
            setStorage(`${options?.key ?? __pinia_key__}-${store.$id}`,toRaw(store.$state))
        });
        console.log(store,'store');
        return {...data}
    }
}
export default piniaPlugin;

在main.js中引入并注册

import './assets/main.css'
import App from './App.vue'
import { createApp } from 'vue'
import { createPinia } from 'pinia'  // 第一步
import piniaPlugin from './plugin/piniaPlugin' // 第二步
import router from './router'
const app = createApp(App)
const store = createPinia();
store.use(piniaPlugin({ // 第三步
    key: "pinia"
}))
app.use(store) // 第四步
app.use(router)
app.mount('#app')

猜你喜欢

转载自blog.csdn.net/xyphf/article/details/134417415