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路由会比根组件先执行,所以我应该如何改进这些代码呢?
回复
1个回答

test
2024-07-15
建议把异步的前置校验单独包装起来,完成后再执行 app.mount,类似
beforeAppMount()
.then(() => {
app.mount('#app')
})
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容