我有以下模块:
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.ProfileData
或this.$store.ajaxData
,而this.$store
已定义且我已经能够阅读它。我还在浏览器的控制台中看到ProfileData
对象添加到商店的_modules
属性中。
访问注册到Vuex
的模块我做错了什么?我怎样才能访问这些?
答案 0 :(得分:9)
访问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>
这取决于它们是否是命名空间。见演示(评论中的解释):
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>
答案 1 :(得分:0)
我看到您使用key:value添加了模块,访问模块的密钥是 Profile 。尝试使用它来调用模块,或直接定义模块设置,而不使用 Profile 键:
modules: {
ProfileData
}