天天看點

Vuex中的Module

Vuex中的Module

一、認識Module

  1. Module是子產品的意思, 為什麼在Vuex中我們要使用子產品呢?
由于使用單一狀态樹,應用的所有狀态會集中到一個比較大的對象。當應用變得非常複雜時,store 對象就有可能變得相當臃腫。為了解決這個問題,Vuex 允許我們将

store

分割成子產品(module)。每個子產品擁有自己的

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局部狀态

  1. 上面的代碼中, 我們已經有了整體的組織結構, 下面我們來看看具體的局部子產品中的代碼如何書寫.
    • 我們在

      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的寫法

  1. 局部狀态通過

    context.state

    暴露出來,根節點狀态則為

    context.rootState

const moduleA = {
  // ...
  actions: {
    incrementIfOddOnRootSum ({ state, commit, rootState }) {
      if ((state.count + rootState.count) % 2 === 1) {
        commit('increment')
      }
    }
  }
}
           
  1. 對于子產品内部的

    getter

    ,根節點狀态會作為第三個參數暴露出來:
const moduleA = {
  // ...
  getters: {
    sumWithRootCount (state, getters, rootState) {
      return state.count + rootState.count
    }
  }
}