利用watch深度监听 通过监听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 import { createApp, watch } from "vue" ;import { createPinia } from "pinia" ;import App from "./App.vue" ;import router from "./router" ;const app = createApp (App );const pinia = createPinia ();app.use (pinia); const piniaState = localStorage .getItem ("piniaState" );if (piniaState) { pinia.state .value = JSON .parse (piniaState); } watch ( pinia.state , (state ) => { localStorage .setItem ("piniaState" , JSON .stringify (state)); }, { deep : true } ); app.use (router); app.mount ("#app" );
利用plugins实现 plguins提供了针对每个store的颗粒度操作,我们利用其中的store.$subscribe()和store.$patch就可以做到持久化的作用,再通过options.persist属性设置来进一步控制持久化的开关。
持久化插件函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import type { PiniaPluginContext } from "pinia" ;declare module "pinia" { export interface DefineStoreOptionsBase <S extends StateTree , Store > { persist?: boolean; } } export default function ({ store, options }: PiniaPluginContext ) { if (!options.persist ) return ; const key = store.$id ; store.$subscribe((mutation, state ) => { localStorage .setItem (key, JSON .stringify (state)); }); const piniaState = localStorage .getItem (key); if (piniaState) { store.$patch(JSON .parse (piniaState)); } }
在入口文件使用:
1 2 3 4 5 6 7 8 9 import { createApp } from "vue" ;import { createPinia } from "pinia" ;import myPluginPersistedstate from "@/stores/plugins/persistedstate" ;const app = createApp (App );const pinia = createPinia ();pinia.use (myPluginPersistedstate); app.use (pinia);
在需要持久化的store中设置persist: true
1 2 3 4 5 6 7 8 9 10 import { defineStore } from "pinia" ;export const useCounterStore = defineStore ({ id : "counter" , state : () => ({ counter : 0 , }), persist : true , });
使用第三方插件 一些现成的第三方插件(建议:pinia-plugin-persistedstate ),可以提供更精细化的控制,比如:开启持久化、缓存方式、自定义缓存key等。
参考