首页 文章

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

提问于
浏览
3

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

{
  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时,就像路由防护中显示的那样,我收到一个错误:

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

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

1 回答

  • 9

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

    在一些教程之后,我有 store.js 定义了我的商店,然后我在我的 router.js 中导入它,如下所示:

    import store from './store'
    

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

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

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

相关问题