【问题标题】:Vuex store is undefined in vue-routerVuex 存储在 vue-router 中未定义
【发布时间】: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 中的storeundefined。我已经检查了几次所有的导入、路线和名称,它们都很好。

由于我在storestore 中导入routerrouter 中的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


【解决方案1】:

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

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

【讨论】:

  • 删除导入它可以工作,但此时 $store 未定义:imgur.com/a/ZVKV5Hi。但只是第一次加载该页面。
  • undefined 变量的任何解决方案?
猜你喜欢
  • 2021-07-25
  • 2019-02-03
  • 2020-05-01
  • 2018-01-16
  • 2019-03-21
  • 2020-02-15
  • 2023-02-09
  • 2018-10-11
  • 2017-07-25
相关资源
最近更新 更多