pinia 数据持久化插件 pinia-plugin-persist

用法地址:https://seb-l.github.io/pinia-plugin-persist/

安装:

npm i pinia-plugin-persist --save --include=dev

引入

src目录下创建文件夹store,store目录下创建index.ts 内容如下

import { createPinia } from "pinia";
import piniaPersist from "pinia-plugin-persist";

const pinia = createPinia();
pinia.use(piniaPersist);

export default pinia;

main.ts 引入pinia内容如下:

import { createApp } from "vue";
import App from "./App.vue";
import pinia from "./store";

const app = createApp(App);
app.use(pinia);
app.mount("#app");

用法 示例如下 其他的看看说明文档就行了

https://seb-l.github.io/pinia-plugin-persist/

import { getToken } from "/@utils/tokenUtil";
import { login } from "/@api/userApi";
import cookieUtil from "/@/utils/cookieUtil";
import router from "../../router";
import { ElMessage } from "element-plus";
import { defineStore } from "pinia";

export const userStore = defineStore("userStore", {
  state: () => ({
    token: getToken(),
    roles: [],
    permissions: [],
    menus: [],
  }),

  persist: {
    enabled: true,
    strategies: [
      { storage: localStorage, paths: ["token", "menus"] },
    ],
  },
  getters: {
    getToken(state: { token: string }): string {
      return state.token;
    },
  },

  actions: {
    setToken(value: string) {
      this.token = value;
    },

    Login(userInfo: any) {
      login(userInfo)
        .then((res: any) => {
          debugger;
          if (res.data.errorCode === "00000") {
            let r = res.data.data;
            this.token = r.accessToken;
            cookieUtil.cookieRemove("LOGIN_CAPTCHA_CODE");
            console.log(r.menus);
            this.menus = r.menus;
            //异步获取用户权限数据 TODO
            ElMessage({
              message: "登陆成功", //提示的信息
              type: "success", //类型是成功
              //offset:225,  //距离窗口顶部的偏移量,建议不设置
              duration: 500, //显示时间, 毫秒。设为 0 则不会自动关闭,建议1200
              onClose: () => {
                //跳转页面或执行方法
                router.push("/index");
              },
            });
          }
        })
        .catch(() => {
          console.log("登陆失败");
        });
    },
  },
});

你可能感兴趣的:(pinia 数据持久化插件 pinia-plugin-persist)