Arr*_*rrr 2 vue.js vue-component vuex vuejs2 vuex-modules
我有以下模块:
export const ProfileData = {
state: {
ajaxData: null;
},
getters: {/*getters here*/},
mutations: {/*mutations here*/},
actions: {/*actions here*/}
}
Run Code Online (Sandbox Code Playgroud)
这个模块在我的全球商店注册:
import {ProfileData} from './store/modules/ProfileData.es6'
const store = new Vuex.Store({
modules: {
ProfileData: ProfileData
}
});
Run Code Online (Sandbox Code Playgroud)
我也使用了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什么?我怎样才能访问这些?
acd*_*ior 11
访问Module的本地状态的格式是$store.state.moduleName.propertyFromState.
所以你会用:
this.$store.state.ProfileData.ajaxData
Run Code Online (Sandbox Code Playgroud)
演示:
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)
}
})Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
这取决于它们是否是命名空间.见演示(评论中的解释):
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'])
}
})Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)