Vuex 无法读取未定义的 属性

Vuex Cannot read property of undefined

我正在尝试使用 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 错误。有什么我想念的吗?

猜测,这可能适用于您当前正在做的事情: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

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