我有一个路由器和一个全局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;
}
}
我的问题是store
中的router.js
是undefined
。我已经多次检查了所有的进口,路线和名称,而且它们很好。
由于我在router
中导入store
而在store
中导入router
,这可能是循环引用的问题吗?
如果这是问题,我如何从商店的路由器或路由器访问商店?
编辑
我试图从商店中删除路由器导入,除了以下情况外它工作正常:
router.push({
path: "/"
});
因为router
不是进口的。
编辑:ADDED @ 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.js
避免在router.app
中导入存储,router.app.$store
提供了路由器注入的关联Vue实例的引用。有了它,你可以通过router.beforeEach((to, from, next) => {
/* ... */
if (!router.app.$store.getters.getAccessToken) {
next("/access/login");
}
});
到达商店:
qazxswpoi