从 Vuex Store 访问模块

Access module from Vuex Store

我有以下模块:

export const ProfileData = {
    state: {
        ajaxData: null;
    },
    getters: {/*getters here*/},
    mutations: {/*mutations here*/},
    actions: {/*actions here*/}
}

并且此模块已在我的全球商店中注册:

import {ProfileData} from './store/modules/ProfileData.es6'
const store = new Vuex.Store({
    modules: {
       ProfileData: ProfileData
    }
});

我也使用了 Vue.use(Vuex) 并在 new Vue({ store: store}) 中正确设置了商店。但是,当我尝试通过 this.$store.ProfileData.ajaxData 在我的组件之一中访问属于 ProfileData 模块的 ajaxData 时,控制台显示 undefined 错误。读取 this.$store.ProfileDatathis.$store.ajaxData 也是如此,而 this.$store 已定义并且我已经能够读取它。我还看到 ProfileData 对象已添加到浏览器控制台中商店的 _modules 属性。

我在访问注册到 Vuex 的模块时做错了什么?我怎样才能访问这些?

我看到您使用 key:value 添加了模块,访问您的模块的密钥是 Profile。尝试使用它来调用您的模块,或者直接定义模块设置,而无需 Profile key:

modules: {
    ProfileData
}

直接访问 Vuex 模块的状态

访问 Module's local state 的格式是 $store.state.moduleName.propertyFromState

所以你会使用:

this.$store.state.ProfileData.ajaxData

演示:

const ProfileData = {
  state: {ajaxData: "foo"}
}
const store = new Vuex.Store({
  strict: true,
  modules: {
    ProfileData
  }
});
new Vue({
  store,
  el: '#app',
  mounted: function() {
   console.log(this.$store.state.ProfileData.ajaxData)
  }
})
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script src="https://unpkg.com/vuex"></script>

<div id="app">
  <p>ajaxData: {{ $store.state.ProfileData.ajaxData }}</p>
</div>


模块的Getters、Actions、Mutators,如何直接访问?

这取决于它们是否命名空间。查看演示(评论中的解释):

const ProfileDataWithoutNamespace = {
  state: {ajaxData1: "foo1"},
  getters: {getterFromProfileDataWithoutNamespace: (state) => state.ajaxData1}
}
const ProfileDataWithNamespace = {
  namespaced: true,
  state: {ajaxData2: "foo2"},
  getters: {getterFromProfileDataWithNamespace: (state) => state.ajaxData2}
}
const store = new Vuex.Store({
  strict: true,
  modules: {
    ProfileDataWithoutNamespace,
    ProfileDataWithNamespace
  }
});
new Vue({
  store,
  el: '#app',
  mounted: function() {
    // state is always per module
   console.log(this.$store.state.ProfileDataWithoutNamespace.ajaxData1)
    console.log(this.$store.state.ProfileDataWithNamespace.ajaxData2)
    // getters, actions and mutations depends if namespace is true or not
    // if namespace is absent or false, they are added with their original name
    console.log(this.$store.getters['getterFromProfileDataWithoutNamespace'])
    // if namespace is true, they are added with Namespace/ prefix
    console.log(this.$store.getters['ProfileDataWithNamespace/getterFromProfileDataWithNamespace'])
  }
})
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script src="https://unpkg.com/vuex"></script>

<div id="app">
  <p>Check the console.</p>
</div>