7

我有以下模块:

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})。但是,当我尝试访问ajaxData属于该ProfileData模块的内容时,在我的一个组件中this.$store.ProfileData.ajaxData,控制台显示undefined错误。阅读this.$store.ProfileDataor this.$store.ajaxData, whilethis.$store定义也是如此,我已经能够阅读它。我还在浏览器的控制台中看到ProfileData添加到_modules商店属性的对象。

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

4

2 回答 2

24

直接访问 Vuex 模块的状态

访问模块本地状态的格式是$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>


模块的Getter、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>

于 2018-04-05T17:54:11.613 回答
0

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

modules: {
    ProfileData
}
于 2018-04-05T17:46:33.023 回答