一、vuex中的模块化(modules)和命名空间(namespaced)
1、vuex模块化的原因
vuex维护的是一个单一的状态树,对于复杂的vue项目,若只有一个store,则该store就会非常臃肿难以维护,为了解决这个问题,vuex允许在vue项目中将store进行模块化的处理,即可以将一个大的store分解成若干个小的store,每个store都有自己的state、mutation、action、getter
2、命名空间
(1)在默认情况下,模块内部的state、mutation、action、getter是全局的,即所有组件都可以使用
(2)若想让store有更好的封装性和复用性、在使用不会产生歧义,可以在store定义时加入 namespaced:true配置,当模块注册后,所有的state、mutation、action、getter都会根据模块注册的路径调整命名
二、vuex中的辅助函数(四大函数/map写法)
1、…mapState:用于解构state中状态属性
//基础写法:
count(){
return this.$store.state.cout
}
//简化写法
...mapState(['count'])
2、…mapGetters:用于解构getters中定义的方法
//基础写法
getAge() {
return this.$store.getters.getAge
}
//简化写法
...mapGetters([''])
3、…mapMutations:用于解构mutations中的方法,注意传参:在调用时直接传参
//基础写法
handlerAdd(){ //同步加1:触发mutations中的addCount方法
this.$store.commit('addCount',{ num: 1 })
},
handlerSub(){ //同步减1:触发mutations中的subCount方法
this.$store.commit('subCount',{ num: 1 })
}
//简化写法
...mapMutations({
handlerAdd: 'addCount',
handlerSub: 'subCount'
}),
//html中直接传参的写法
<button @click="handlerAdd({num:1})">同步加1</button>
<button @click="handlerSub({num:1})">同步减1</button>
4、…mapActions:用于解构actions中的方法
//基础写法
handlerAddAsyn(){ //异步加1:触发actions中addCountAsyn方法
this.$store.dispatch('addCountAsyn')
},
handlerSubAsyn(){ //异步减1:触发actions中subCountAsyn方法
this.$store.dispatch('subCountAsyn')
}
//简化写法
...mapActions({
handlerAddAsyn: 'addCountAsyn',
handlerSubAsyn: 'subCountAsyn'
})