Vuex 的五种属性及其作用

State、Getter、Mutation、Action、Module 的功能和使用场景

问题

Vuex 有哪些核心属性,它们分别用来解决什么问题?

解答

Vuex 有五种核心属性:State、Getter、Mutation、Action、Module。

State

State 是 Vuex 的单一状态树,用一个对象包含全部应用层级状态,作为唯一数据源(SSOT)存在。每个应用只包含一个 store 实例。

单一状态树的优势是可以直接定位任一状态片段,在调试时能轻易获取整个应用状态的快照。

const store = new Vuex.Store({
  state: {
    count: 0,
    userInfo: {}
  }
})

Getter

Getter 用于从 state 派生出新的状态,类似 Vue 的 computed 属性。当需要对状态进行过滤、计算等处理时使用。

const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, done: true },
      { id: 2, done: false }
    ]
  },
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }
})

Mutation

Mutation 是更改 Vuex store 中状态的唯一方法。每个 mutation 都有一个事件类型(type)和一个回调函数(handler)。

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state, payload) {
      state.count += payload
    }
  }
})

// 提交 mutation
store.commit('increment', 10)

Action

Action 用于处理异步操作,它提交的是 mutation 而不是直接变更状态。

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++
    }
  },
  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => {
        commit('increment')
      }, 1000)
    }
  }
})

// 分发 action
store.dispatch('incrementAsync')

Module

Module 用于将 store 分割成模块,解决单一状态树在复杂应用中变得臃肿的问题。每个模块拥有自己的 state、mutation、action、getter,还可以嵌套子模块。

const moduleA = {
  state: { count: 0 },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: { count: 0 },
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

关键点

  • State 是单一状态树,作为唯一数据源存储应用状态
  • Getter 用于派生状态,类似 computed 属性
  • Mutation 是同步更改状态的唯一方式,通过 commit 提交
  • Action 处理异步操作,通过 dispatch 分发,最终提交 mutation
  • Module 用于模块化管理,避免 store 过于臃肿