利用watch
深度监听
通过监听pinia状态变化来缓存,特点是简单粗暴
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);
// pinia状态持久化
const piniaState = localStorage.getItem("piniaState");
if (piniaState) {
pinia.state.value = JSON.parse(piniaState);
}
watch(
pinia.state,
(state) => {
// persist the whole state to the local storage whenever it changes
localStorage.setItem("piniaState", JSON.stringify(state));
},
{ deep: true }
);
app.use(router);
app.mount("#app");
利用plugins
实现
plguins
提供了针对每个store
的颗粒度操作,我们利用其中的store.$subscribe()
和store.$patch
就可以做到持久化的作用,再通过options.persist
属性设置来进一步控制持久化的开关。
持久化插件函数:
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));
}
}
在入口文件使用:
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
import { defineStore } from "pinia";
export const useCounterStore = defineStore({
id: "counter",
state: () => ({
counter: 0,
}),
persist: true,
});
使用第三方插件
一些现成的第三方插件(建议:pinia-plugin-persistedstate),可以提供更精细化的控制,比如:开启持久化、缓存方式、自定义缓存key等。