【发布时间】:2019-09-09 07:32:32
【问题描述】:
我有一个路由器和一个全局 beforeEach 挂钩来验证身份验证。
import store from "@/store/store";
const router = new Router({
// routes...
});
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!store.getters.getAccessToken) { //undefined store
next("/access/login");
}
}
else {
next();
}
});
export default router;
在我的store/store.js 文件中,我有一个动作请求验证用户/密码,然后尝试重定向到/ 路由(受保护的路由)。
import router from "@/router";
//state, getters...
actions: {
login({commit}, authData) {
// axios instance prototyped into vue $http object
this._vm.$http.post("/auth/login", authData)
.then(response => {
commit("saveToken", response.data.token);
})
.catch((error) => {
commit("loginError", error.response.data);
});
}
},
mutations: {
saveToken(state, token) {
state.accessToken = token;
router.push({
path: "/"
});
},
loginError(state, data) {
return data.message;
}
}
我遇到的问题是router.js 中的store 是undefined。我已经检查了几次所有的导入、路线和名称,它们都很好。
由于我在store 和store 中导入router 和router 中的store,循环引用会出现问题吗?
如果是这个问题,如何从路由器或路由器从商店访问商店?
编辑
我试图从商店中删除路由器导入,它工作正常,但以下情况除外:
router.push({
path: "/"
});
因为router 没有被导入。
编辑:添加@tony19 解决方案
我已经应用了@tony19 提供的解决方案并且效果很好,但是当我访问/ 路由时,router.app.$store 是未定义的。
固定代码:
router.beforeEach((to, from, next) => {
console.log(`Routing from ${from.path} to ${to.path}`);
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!router.app.$store.getters["authentication/getAccessToken"]) {
next("/access/login");
}
else {
next();
}
}
else {
next();
}
});
带有调试会话的图像:
【问题讨论】:
-
只是一个愚蠢的问题,您确定您正确导出了商店吗?当您删除存储中的路由器引用时发生了什么?
-
一切都按预期工作,但由于未导入路由器,无法生成
router.push({ path: "/" });。
标签: javascript vue.js vuejs2 vuex vue-router