这是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路由会比根组件先执行,所以我应该如何改进这些代码呢?
建议把异步的前置校验单独包装起来,完成后再执行 app.mount,类似