gpt4 book ai didi

javascript - Vuex 商店在 vue-router 中未定义

转载 作者:行者123 更新时间:2023-11-30 14:04:16 24 4
gpt4 key购买 nike

我有一个路由器和一个全局 beforeEach Hook 来验证身份验证。

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 中的 storeundefined。我已经多次检查所有导入、路由和名称,它们都很好。

这可能是循环引用的问题,因为我在 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();
}
});

带有调试 session 的图像:

enter image description here

最佳答案

这确实是循环引用造成的。您可以使用 router.app 避免在 router.js 中导入商店,它提供了路由注入(inject)到的关联 Vue 实例的引用。这样,您就可以通过 router.app.$store 前往商店:

router.beforeEach((to, from, next) => {
/* ... */
if (!router.app.$store.getters.getAccessToken) {
next("/access/login");
}
});

关于javascript - Vuex 商店在 vue-router 中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55754891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com