利用watch深度监听

通过监听pinia状态变化来缓存,特点是简单粗暴

  1. import { createApp, watch } from "vue";
  2. import { createPinia } from "pinia";
  3. import App from "./App.vue";
  4. import router from "./router";
  5. const app = createApp(App);
  6. const pinia = createPinia();
  7. app.use(pinia);
  8. // pinia状态持久化
  9. const piniaState = localStorage.getItem("piniaState");
  10. if (piniaState) {
  11. pinia.state.value = JSON.parse(piniaState);
  12. }
  13. watch(
  14. pinia.state,
  15. (state) => {
  16. // persist the whole state to the local storage whenever it changes
  17. localStorage.setItem("piniaState", JSON.stringify(state));
  18. },
  19. { deep: true }
  20. );
  21. app.use(router);
  22. app.mount("#app");

利用plugins实现

plguins提供了针对每个store的颗粒度操作,我们利用其中的store.$subscribe()store.$patch就可以做到持久化的作用,再通过options.persist属性设置来进一步控制持久化的开关。

持久化插件函数:

  1. import type { PiniaPluginContext } from "pinia";
  2. declare module "pinia" {
  3. export interface DefineStoreOptionsBase<S extends StateTree, Store> {
  4. persist?: boolean;
  5. }
  6. }
  7. export default function ({ store, options }: PiniaPluginContext) {
  8. if (!options.persist) return;
  9. const key = store.$id;
  10. store.$subscribe((mutation, state) => {
  11. localStorage.setItem(key, JSON.stringify(state));
  12. });
  13. const piniaState = localStorage.getItem(key);
  14. if (piniaState) {
  15. store.$patch(JSON.parse(piniaState));
  16. }
  17. }

在入口文件使用:

  1. import { createApp } from "vue";
  2. import { createPinia } from "pinia";
  3. import myPluginPersistedstate from "@/stores/plugins/persistedstate";
  4. const app = createApp(App);
  5. const pinia = createPinia();
  6. pinia.use(myPluginPersistedstate);
  7. app.use(pinia);

在需要持久化的store中设置persist: true

  1. import { defineStore } from "pinia";
  2. export const useCounterStore = defineStore({
  3. id: "counter",
  4. state: () => ({
  5. counter: 0,
  6. }),
  7. persist: true,
  8. });

使用第三方插件

一些现成的第三方插件(建议:pinia-plugin-persistedstate),可以提供更精细化的控制,比如:开启持久化、缓存方式、自定义缓存key等。

参考