在组件中使用 this.$store.commit('xxx',xxx); 发现控制台一直报错,检查命名后发现也没有错误

后不经意间发现代码中有一个陌生的字眼namespaced: true,在网上对它进行搜索后得以解决
原来vuex中的store分模块管理时,需要在store的index.js中引入各个模块,为了解决不同模块命名冲突的问题,将不同模块的namespaced:true,之后在不同页面中引入getter、actions、mutations时,需要加上所属的模块名
那么当namespaced: true如何获取使用vuex中的数据?
state
//获取。不管为true为false
this.$store.state.schedule.pages
//辅助函数
...mapState({
pages: state=>state.home.pages,
}),getters
//获取
this.$store.getters['schedule/changepg']
//辅助函数
...mapGetters({
total:'schedule/changepg'
})mutations
//commit调用mutation更新
changepg(){
this.$store.commit('home/changepg',5);
}
//辅助函数
...mapMutations({
changepg: 'home/changepg',
})
actions
//dispatch派发actions
change(){
this.$store.dispatch('home/changepg',5)
}
//辅助函数
...mapActions({
changepg: 'home/changepg',
}),也就是在methods中需要写成这种格式才得以解决

当Vuex的store启用namespaced:true时,需要在访问state、getters、mutations和actions时添加模块名前缀。例如,访问state使用this.$store.state.moduleName.stateItem,getters用this.$store.getters[moduleName/getterName],commit和dispatch也需类似格式。辅助函数如mapState、mapGetters等同样需要指定模块名。
1720

被折叠的 条评论
为什么被折叠?



