问题
I am trying to guard my routes by checking if the user is authenticated, this is the example route:
{
path: '/intranet',
component: search,
meta: { requiresAuth: true },
props: {
tax: 'type',
term: 'intranet-post',
name: 'Intranet'
}
},
And I am setting the guard like this:
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
let authenticated = this.$store.getters['auth/getAuthenticated'];
if (!authenticated) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next()
}
})
This is the vuex module for auth:
import Vue from "vue";
export default {
namespaced: true,
state: {
authenticated: !!localStorage.getItem("token"),
token: localStorage.getItem("token")
},
mutations: {
login: function(state, token){
state.authenticated = true;
state.token = token;
},
logout: function(state){
state.authenticated = false;
state.token = '';
}
},
actions: {
login: function({commit}, token){
localStorage.setItem('token', token);
commit('login', token);
},
logout: function({commit}){
localStorage.removeItem("token");
commit('logout');
}
},
getters: {
getToken: (state) => state.token,
getAuthenticated: (state) => state.authenticated,
}
}
But, when I try to access the auth getter like it is shown in the route guard, I get an error:
Cannot read property 'getters' of undefined
What am I doing wrong, how can I fix this?
回答1:
The error message states that this.$store
is undefined when it tries to access this.$store.getters
, so the problem seems that the store is not initialized or set up the way you expect it to within the router. Accessing the namespaced getters using .getters['name/getter']
is in itself correct.
Following some tutorials, I have store.js
which defines my store, and then I import it in my router.js
like this:
import store from './store'
and then access it directly with store
instead of this.$store
:
let authenticated = store.getters['auth/getAuthenticated'];
I think the problem is that this.$store
is automatically added to Vue-Components, but the router is not really a component, and is thus missing the $store
-member. Importing the store works around this.
来源:https://stackoverflow.com/questions/46908306/vuex-accessing-namespaced-module-getters-in-vue-router