【问题标题】:Vue - Modules of store not accessible in componentVue - 组件中无法访问的商店模块
【发布时间】:2019-03-07 08:59:45
【问题描述】:

我的 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' of undefined"

【问题讨论】:

    标签: javascript vue.js frontend vuex


    【解决方案1】:

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

    只需在文件末尾添加:

    export default authToken;
    

    【讨论】:

    • 太棒了!这似乎让我可以访问我的 authToken 状态。谢谢!但是,我似乎仍然无法使用吸气剂。我在使用 this.$store.state.authToken.getters.isAuthenticated 时遇到了同样的错误,但如果我使用 his.$store.state.authToken.token,我可以访问我的令牌值。这是为什么呢?
    • 当您尝试使用 this.$store.state.authToken.getters.isAuthenticated 时会发生什么?另外,我建议您使用地图助手 (vuex.vuejs.org/guide/getters.html#the-mapgetters-helper)。它可能会帮助您获得更简洁的代码。
    • 好吧想通了,我显然可以通过使用 this.$store.getters.isAuthenticated 来访问我的 authtoken getter
    • 啊,那可能是因为您没有在商店选项中设置namespaced: true。如果它解决了您的问题,请不要忘记将答案标记为已接受,以便其他用户/读者可以更轻松地看到修复。
    猜你喜欢
    • 1970-01-01
    • 2017-04-17
    • 2021-05-07
    • 2018-02-28
    • 2021-06-05
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多