Vuex store is undefined in vue-router

有些话、适合烂在心里 提交于 2020-01-23 03:44:05

问题


I have a router and a global beforeEach hook to validate auth.

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).

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. 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?

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.

EDIT: ADDED @tony19 SOLUTION

I've applied the solution that @tony19 provides and it works fine, but when I access the / route, router.app.$store is undefined.

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:


回答1:


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. With that, you could get to the store by router.app.$store:

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


来源:https://stackoverflow.com/questions/55754891/vuex-store-is-undefined-in-vue-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!