Vuex 在 vue 路由器中访问命名空间模块 getter

Vuex accessing namespaced module getters in vue router

我试图通过检查用户是否经过身份验证来保护我的路由,这是示例路由:

{
  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 模块:

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 时,就像它在路由守卫中显示的那样,我得到一个错误:

Cannot read property 'getters' of undefined

我做错了什么,我该如何解决?

错误消息指出 this.$store 在尝试访问 this.$store.getters 时未定义,因此问题似乎是存储未初始化或未按照您期望的方式在路由器中设置.使用 .getters['name/getter'] 访问命名空间的 getters 本身是正确的。

按照一些教程,我有 store.js 来定义我的商店,然后我将它导入到我的 router.js 中,如下所示:

import store from './store'

然后直接用 store 访问它而不是 this.$store:

let authenticated = store.getters['auth/getAuthenticated'];

我认为问题在于 this.$store 自动添加到 Vue-Components,但路由器并不是真正的组件,因此缺少 $store-成员。导入商店可以解决这个问题。