// 在 *.ts/js 文件中使用 pinia 报错解决方法(未删减完全)

// 文件路径

src
  store
   -index.ts
   -user.store.ts
   -user.store.ts
  router
   -index.ts

// 使用方法 @/*.ts

import { $Store } from '@/store';

console.log($Store.UserStore.token)

// @/router/index.ts

import { $Store } from "@/store/index";

router.beforeEach((to, from, next) => {
  // 制作js 使用的store 重做数据
  Object.keys(Stores.DefStore).map(item => {
    if(item != '$Store') {
      console.log(item)
      // @ts-ignore
      $Store[item] = eval(`Stores.DefStore.${item}.useStore()`)
    }
  })
  console.log(from.path, to.path);
  const superlative = ['/', '/login', '/404'];
  // #权鉴 部分页面不需要校验 token 也可进入
  if(superlative.includes(to.path)) {
    next();
  } else {
    if($Store.UserStore.token)
      next()
    else
      next('/login')
  }
});

// @/store/index.ts

import { createPinia } from "pinia";
import type { App } from "vue";
import router from '@/router'

const Store = createPinia();

export function setupPinia(app: App) {
  Store.use(({ store }) => {
    // ...这里安装插件
    store.$router = router
  }), app.use(Store);
}

// export * from './use.store.ts'
// export * from './app.store.ts'

import * as UserStore from "./user.store";
import * as SourceStore from "./source.store";
import * as ControlStore from "./control.store";
import * as EditorStore from "./editor.store";
export const DefStore = { UserStore, SourceStore, ControlStore, EditorStore };

// js 使用公共的 Store 数据
export const $Store:any = {};

export default Store;

// @/store/user.store.ts

// @ts-check
import { defineStore, acceptHMRUpdate } from "pinia";
import { Message } from "@/Utils/ajax/messages";
import { api_login } from "@/api/user.api"
import { sha256 } from 'js-sha256'
import { getToken, setToken } from '@/storage/user.storage'

// 导入 路由模块
import router from "@/router/index";
// import type { RouteParamsRaw } from "vue-router";

interface UserState {
  session: string | null;
  token: string | null;
  account: string | null;
  uId: string | null;
  uName: string | null;
  uType: string | null;
}
const token = getToken();
export const useStore = defineStore("user", {
  state: (): UserState => ({
    session: null,
    token: token,
    account: null,
    uId: null,
    uName: null,
    uType: null,
  }),

  actions: {
    logout() {
      this.$patch({
        uName: "",
        uType: "user",
      });

      // we could do other stuff like redirecting the user
    },

    /**
     * Attempt to login a user
     * @param {string} user
     * @param {string} password
     */
    login(user: any, password: any) {
      api_login(user, sha256(password)).then(res => {
        setToken(res.data);
        this.$patch({ token: res.data });
        // @ts-ignore
        router.push({ name: "Dashboard" });
        Message.suc('登录成功')
      }).catch(err => {
        console.log(err)
      });
    },
  },
});

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useStore, import.meta.hot));
}

原文地址:http://www.cnblogs.com/qoon-f/p/16850919.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性