gpt4 book ai didi

vue.js - 从 Vuex Store 访问模块

转载 作者:搜寻专家 更新时间:2023-10-30 22:29:29 25 4
gpt4 key购买 nike

我有以下模块:

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

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

最佳答案

直接访问 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>

关于vue.js - 从 Vuex Store 访问模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49678333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com