Vuex允许将store分割成模块,因为当使用单一状态树的时候,应用的所有状态集中到一个比较大的对象,导致store对象相当臃肿。分割后的每个模块拥有自己的state、mutation、action、getter,甚至是嵌套子模块。
//定义两个store的子模块
const moduleA={
state:{...},
mutations:{...},
actions:{...},
getters:{...}
}
const moduleB={
state:{...},
mutations:{...},
actions:{...},
getters:{...}
}
//定义store
const store=new Vuex.Store({
moudules:{
a:moduleA,
b:moduleB
}
})
store.state.a //moduleA的状态
store.state.b //moduleB的状态
模块的局部状态
对于模块内部的mutation和getter,接收的第一个参数就是模块的局部状态对象。
const moduleA={
state:{ count: 0 },
mutations:{
increment(state){
state.count++
}
},
getters:{
doubleCount(state){
return state.count*2
}
}
}
对于模块内部的action,局部状态通过context.state暴露出来,根节点状态则为context.rootState
const moduleA={
actions:{
inrementIfOddOnRootSum({ state,commit,rootState}){
if((state.count+rootState.count)%2===1){
commit('increment')
}
}
}
}
对于模块内部的getter,根节点状态会作为第三个参数暴露出来:
const mduleA={
getters:{
sumWithRootCount(state,getters,rootState){
return state.count+rootState.count
}
}
}