Vuex中的Module
一、認識Module
- Module是子產品的意思, 為什麼在Vuex中我們要使用子產品呢?
由于使用單一狀态樹,應用的所有狀态會集中到一個比較大的對象。當應用變得非常複雜時,store 對象就有可能變得相當臃腫。為了解決這個問題,Vuex 允許我們将分割成子產品(module)。每個子產品擁有自己的
store
、甚至是嵌套子子產品——從上至下進行同樣方式的分割:
state、mutation、action、getter
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的狀态
store.state.b // -> moduleB 的狀态
二、Module局部狀态
- 上面的代碼中, 我們已經有了整體的組織結構, 下面我們來看看具體的局部子產品中的代碼如何書寫.
- 我們在
中添加moduleA
state、mutations、getters
-
和mutation
接收的第一個參數是局部狀态對象getters
- 我們在
const moduleA = {
state: { count: 0 },
mutations: {
increment (state) {
// 這裡的 `state` 對象是子產品的局部狀态
state.count++
}
},
getters: {
doubleCount (state) {
return state.count * 2
}
}
}
三、子產品内Actions的寫法
- 局部狀态通過
暴露出來,根節點狀态則為context.state
context.rootState
const moduleA = {
// ...
actions: {
incrementIfOddOnRootSum ({ state, commit, rootState }) {
if ((state.count + rootState.count) % 2 === 1) {
commit('increment')
}
}
}
}
- 對于子產品内部的
,根節點狀态會作為第三個參數暴露出來:getter
const moduleA = {
// ...
getters: {
sumWithRootCount (state, getters, rootState) {
return state.count + rootState.count
}
}
}