vuex 使用文档小结篇(7)
Modules
使用单一状态树,当应用变的很大的时候,store 对象会变的臃肿不堪。
Vuex 允许我们将store 分割到模块。每一个模块都有自己的state, mutation,action, getters, 甚至是嵌套子模块从上到下进行类似的分割。
const moduleA = {
state: {...},
mutations: {...}
actions: {...}
getters:{...}
}
const moduleA = {
state: {...},
mutations: {...}
actions: {...}
}
const store = new Vuex.Store({
modules: {
a:moduleA,
b:moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
模块的局部状态
对于模块内部的 mutation 和 getter, 接收的第一个参数是模块的局部状态。
const moduleA = {
state: {count:0},
mutations: {
increment (state) {
// state 模块的局部状态
state.count++
}
},
getters: {
doubleCount (state) {
return state.count * 2
}
}
}
同样对于模块内部的action, context.state 是局部状态,根节点的窗台石context.rootState:
const moduleA = {
actions: {
incrementIfOddOnRootSum ({state, commit ,rootState}) {
if((state.count + rootState.count) %2 ===1){
commit('increment')
}
}
}
}
对于模块内部的getter,跟节点状态会作为第三个参数:
const moduleA = {
getters: {
getters: {
sumWithRootCount (state,getters,rootState) {
return state.count + rootState.count
}
}
}
}
内容版权声明:除非注明,否则皆为本站原创文章。
