配置 modules
const store = new Vuex.Store({
modules: {
mkA: {
namespaced: true,
state: {
mkAaaa: '模块a',
},
mutations: {
//定义的是修改state的变量
updatemkA(state) {
state.mkAaaa = '模块aa'
},
},
},
mkB: {
namespaced: true,
state: {
mkBbbb: '模块b',
},
mutations: {
//定义的是修改state的变量
updatemkB(state) {
state.mkBbbb = '模块bb'
},
},
},
},
})
配置 getters
getters: {
userName(state) {
return state.user.username
},
mkA: (state) => state.mkA.mkAaaa,
mkB: (state) => state.mkB.mkBbbb,
},
mk.vue的配置
<template>
<div>
<div>模块a=> {{ $store.state.mkA.mkAaaa }}</div>
<div>模块b=> {{ $store.state.mkB.mkBbbb }}</div>
<div>mapGetters引入模块a=>{{ mkA }}</div>
<div>mapGetters引入模块b=>{{ mkB }}</div>
<!-- <button @click="updatemkA">1更新子模块的MK</button>
<button @click="testFn">2调用子模块的MK</button> -->
<button @click="updatemkA">3createNamespacedHelpers方式</button>
</div>
</template>
<script>
// import { mapGetters, mapMutations, createNamespacedHelpers } from 'vuex'
import { mapGetters, createNamespacedHelpers } from 'vuex'
const { mapMutations } = createNamespacedHelpers('mkA')
export default {
name: '',
components: {},
props: {},
data() {
return {}
},
computed: {
...mapGetters(['mkA', 'mkB']),
},
watch: {},
created() {},
mounted() {},
methods: {
// updatemkA() {
// //1传统方式不加namespaced时代表全局使用,但是加上后再使用报错
// // this.$store.commit('updatemkA')
// //调到加锁状态的mkA方式一 采用路径的形式
// this.$store.commit('mkA/updatemkA')
// },
// //不加路径不会有任何效果
// // ...mapMutations(['updatemkA']),
// // testFn() {
// // this['updatemkB']
// // },
// //方式二 辅助函数带路径
// ...mapMutations(['mkB/updatemkB']),
// testFn() {
// // 注意调用的是个方法要加()
// this['mkB/updatemkB']()
// },
//方式三 创建基于某个命名空间辅助函数
...mapMutations(['updatemkA']),
},
}
</script>
<style lang="less" scoped></style>