【问题标题】:Vuex Cannot read property of undefinedVuex无法读取未定义的属性
【发布时间】:2018-04-21 18:24:25
【问题描述】:

我正在尝试使用 Vuex 处理全局变量,但即使我使用 Vue.use(); 初始化 Vuex,我也会不断收到 undefined 错误。

TypeError: Cannot read property 'isAuth' of undefined

store.js:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  isAuth: true,
});

main.js:

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

我调用isAuth 来查看它的值,如下所示:this.$store.isAuth;,这会导致undefined 错误。

我确实在store.js 中初始化了Vuex,但仍然出现undefined 错误。有什么我遗漏的吗?

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    猜测一下,这可能适用于您当前正在做的事情:this.$store.state.isAuth,但我会像下面那样做。

    我没有像你以前那样使用商店,但在使用模块时没有遇到问题,试试这样:

    // authModule.js
    const state = {
        isAuth: true
    }
    
    const getters = {
        getIsAuth (state) {
            return state.isAuth
        }
    }
    
    export default {
        state,
        getters
    }
    

    然后像这样注册:

    import authModule from './modules/authModule'
    export default new Vuex.Store({
        modules: {
            authModule
        }
    })
    

    然后在你的 vue 实例上:

    import {mapGetters} from 'vuex'
    
    computed: {
        ...mapGetters({
            isAuth: 'getIsAuth'
        })
    }
    

    您现在可以通过this.isAuth 访问。您也可以访问:this.$store.state.authModule.isAuth

    根据他们的文档,这实际上是最佳实践,因为当项目变大时它可以保持整洁。

    【讨论】:

    • 感谢您的回答。我不再收到错误,但我仍然得到undefined 作为isAuth 的值。我应该看到该值还是看到该值为undefined 是否正常?
    • 你不应该看到未定义的,不。如果你从你的 vue 组件中console.log(this),看看你应该看到$store。它有价值吗?您还应该能够深入了解该状态并查看它的价值。那将是一个很好的起点。
    • 我做了一些修改,现在我可以在任何我想看到的地方看到$store。再次感谢您的宝贵时间!
    • 如果你使用直接的 js 而不是 .vue 文件,你会怎么做?
    • @qdeninja 抱歉,这不是我以前做过的,所以不知道。 Vuex 网站应该有一些信息。
    猜你喜欢
    • 1970-01-01
    • 2021-07-07
    • 2020-04-06
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多