Vuex store is undefined in vue-router

2020-07-31 19:14发布

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:

enter image description here

1条回答
乱世女痞
2楼-- · 2020-07-31 20:09

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");
  }
});
查看更多
登录 后发表回答