简体   繁体   English

Vuex 商店在 vue-router 中未定义

[英]Vuex store is undefined in vue-router

I have a router and a global beforeEach hook to validate auth.我有一个路由器和一个全局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;

And in my store/store.js file, I have an action that makes a request to validate user/password, and then tries to redirect to / route (protected route).在我的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;
    }
}

The problem I have is that the store in router.js is undefined .我遇到的问题是router.js中的storeundefined I have checked all imports, routes, and names several times, and they're fine.我已经多次检查了所有导入、路由和名称,它们都很好。

Could it be a problem with the circular reference due to me importing router in the store and store in the router ?由于我在store中导入router并在routerstore ,这可能是循环引用的问题吗?

If that's the problem, how can I access the store from the router or the router from the store?如果这是问题所在,我如何从路由器访问商店或从商店访问路由器?

EDIT编辑

I've tried to remove the router import from the store, and it works fine with the exception of:我试图从商店中删除路由器导入,但它工作正常,但以下情况除外:

router.push({
    path: "/"
});

because router is not imported.因为没有导入router

EDIT: ADDED @tony19 SOLUTION编辑:添加@tony19 解决方案

I've applied the solution that @tony19 provides and it works fine, but when I access the / route, router.app.$store is undefined.我已经应用了 @tony19 提供的解决方案并且它工作正常,但是当我访问/路由时, router.app.$store是未定义的。

The fixed code:固定代码:

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();
    }
});

An image with the debugging session:带有调试会话的图像:

在此处输入图像描述

This is indeed caused by the circular reference.这确实是循环引用造成的。 You could avoid importing the store in router.js by using router.app , which provides a reference the associated Vue instance the router was injected to.您可以通过使用router.app避免在router.js中导入商店,它提供了对路由器注入到的关联 Vue 实例的引用。 With that, you could get to the store by router.app.$store :这样,您就可以通过router.app.$store

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM