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

Lef*_*eff 5 vue-router vuex vuejs2

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

{
  path: '/intranet',
  component: search,
  meta: { requiresAuth: true },
  props: {
    tax: 'type',
    term: 'intranet-post',
    name: 'Intranet'
  }
},
Run Code Online (Sandbox Code Playgroud)

我正在这样设置警卫:

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()
  }
})
Run Code Online (Sandbox Code Playgroud)

这是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,
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试访问auth getter时,就像路由防护中显示的那样,我收到一个错误:

无法读取未定义的属性'getters'

我做错了什么,我该如何解决这个问题?

cel*_*llo 10

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

下面的一些教程,我有store.js定义我的商店,然后我导入它router.js像这样:

import store from './store'
Run Code Online (Sandbox Code Playgroud)

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

let authenticated = store.getters['auth/getAuthenticated'];
Run Code Online (Sandbox Code Playgroud)

我认为问题是this.$store自动添加到Vue-Components,但路由器实际上不是一个组件,因此缺少$store-member.导入商店可以解决这个问题.