Vuex 访问 vue 路由器中的命名空间模块 getter [英] Vuex accessing namespaced module getters in vue router
问题描述
我试图通过检查用户是否通过身份验证来保护我的路线,这是示例路线:
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'
}
},
我是这样设置警卫的:
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()
}
})
这是用于 auth 的 vuex 模块:
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,
}
}
但是,当我尝试访问路由保护中显示的 auth getter 时,出现错误:
But, when I try to access the auth getter like it is shown in the route guard, I get an error:
无法读取未定义的属性getter"
Cannot read property 'getters' of undefined
我做错了什么,我该如何解决?
What am I doing wrong, how can I fix this?
推荐答案
错误消息指出 this.$store
在尝试访问 this.$store.getters<时未定义/code>,所以问题似乎是商店没有按照您期望的方式在路由器内初始化或设置.使用
.getters['name/getter']
访问命名空间的 getter 本身是正确的.
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.
按照一些教程,我有 store.js
定义了我的商店,然后我将它导入到我的 router.js
中,如下所示:
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'
然后直接使用 store
而不是 this.$store
访问它:
and then access it directly with store
instead of this.$store
:
let authenticated = store.getters['auth/getAuthenticated'];
我认为问题是 this.$store
会自动添加到 Vue-Components 中,但是路由器并不是真正的组件,因此缺少 $store
-会员.导入商店可以解决这个问题.
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.
这篇关于Vuex 访问 vue 路由器中的命名空间模块 getter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!