pinia-数据持久化

119 阅读1分钟
import { createPinia } from "pinia";
const pinia = createPinia();
/**
 * pinia-数据持久化
 */
pinia.use((context: any) => {
  const { store } = context;
  let Mkey = `piniaCache_${store.$id}`;
  store.$subscribe(() => {
    localStorage.setItem(Mkey, JSON.stringify(toRaw(store.$state)));
  });
  const obj: any = JSON.parse(localStorage.getItem(Mkey) || "{}");
  const ret: any = {};
  for (let key in store.$state) {
    let row = obj[key];
    if (row != undefined) {
      ret[key] = row;
    }
  }
  if (ret) {
    return ret;
  }
})