第一步对 secure-ls 进行安装:npm install secure-ls
第二步: secure-ls 的引入:import SecureLS from "secure-ls";

点击查看代码

import { ref } from "vue";
import { defineStore } from "pinia";
import type { StorageLike } from "pinia-plugin-persistedstate";
import SecureLS from "secure-ls";
const ls = new SecureLS({
  isCompression: false, //不压缩 //自定义秘钥
  encryptionSecret: "my-secret",
});
export const SelfStorage: StorageLike = {
  setItem(key: string, value: string) {
    //set()的时候对数据进行加密
    ls.set(key, value);
  },
  getItem(key: string): string | null {
    // get()的时候对数据进行解密
    return ls.get(key);
  },
};

export const useStorageStore = defineStore(
  "storage",
  () => {
    const user = ref({
      id: 0,
      name: "",
      apiLevel: "",
      expireTime: 0,
    });
    function removeUser() {
      user.value = {
        id: 0,
        name: "",
        apiLevel: "",
        expireTime: 0,
      };
    }
    return { user, removeUser };
  },
  {
    persist: {
      enabled: true,
      storage: SelfStorage, // 在pinia的使用
    },
  }
);

posted on 2024-11-29 16:56  好久不见-库克  阅读(28)  评论(0编辑  收藏  举报