首页 > 解决方案 > Vue - 组件中无法访问的商店模块

问题描述

我的src/store/modules/authToken.js文件是这样的:

const authToken = {
    state: { 
        token: localStorage.getItem('user-token') || '',
        status: '',
    },
    mutations: {
      authSuccess(state, token) {
          console.log('hellllo')
          state.token = token
          state.status = 'success'
      },

      authFail(state) {
          state.status = 'error'
      }
    },

    getters: {
      isAuthenticated: state => {
          return !!state.token
      },
      authStatus: state => {
          return state.status
      }
    }
}

我的 src/store/store.js 文件是这样的:

import Vue from 'vue'
import Vuex from 'vuex'
import authToken from './modules/authtoken'

Vue.use(Vuex)
Vue.config.devtools = true
export const store = new Vuex.Store({
    modules: {
        authToken
    }
})

在我的 main.js 文件中,我使用的商店如下:

import { store } from './store/store'
new Vue({
  render: h => h(App),
  store,
  router,
}).$mount('#app')

现在,当我尝试访问组件文件中的 autoken 模块时,我无法访问它。我正在这样做。$store.state.authToken.getters.isAuthenticated

但是当我尝试使用它时出现以下错误。

挂载钩子中的错误:“TypeError:无法读取未定义的属性‘isAuthenticated’”

标签: javascriptvue.jsfrontendvuex

解决方案


这是因为您忘记在文件中导出对象src/store/modules/authToken.js。由于没有导出任何内容,因此authToken您提供给商店的变量将是undefined.

只需在文件末尾添加:

export default authToken;

推荐阅读