vue3路由守卫使用pinia的数据时,如何在路由加载前拿到数据?

这是router文件的beforeEach方法

router.beforeEach((to, from, next) => {
  // next();
  if (to.meta.isAdmin) {
    if (useStore().userData.role === "root") {
      next();
    } else {
      next({ name: "Index" });
    }
  } else if (to.meta.isLogin) {//是否需要登录
    if (useStore().ifPassAuth) {//从pinia中拿数据,看是否已经通过登录验证
      next();
      console.log(useStore().ifPassAuth);//(如果在该页面刷新)始终输出false
    } else {
      next({ name: "Login" });
    }
  } else {
    next();
  }
});

这是store文件:

import { defineStore } from "pinia";
import { axiosGet } from "../axios/api";
import { User } from "../Interface/Interface";

export const useStore = defineStore("main", {
  state: () => {
    return {
      ifPassAuth: false,
      userData: {} as User,
    };
  },
  actions: {
    // 验证Token,返回userData
    async authToken() {
      const res = await axiosGet("api/users");
      this.userData = res.data;
      this.ifPassAuth = true;
    },
    // 退出登录
    logout() {
      this.userData = {} as User;
      this.ifPassAuth = false;
    },
  },
});

然后我在App.vue根组件下,执行了登录验证的方法:

const store = useStore();
store.authToken();//store文件中的actions

如果直接跳转路由是可以按照我的想法运行的,但是刷新的话,路由中拿到的store中的
ifPassAuth会始终为初始值false,我了解到vue路由会比根组件先执行,所以我应该如何改进这些代码呢?

阅读 4.3k
1 个回答

建议把异步的前置校验单独包装起来,完成后再执行 app.mount,类似

beforeAppMount()
  .then(() => {
    app.mount('#app')
  })
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题