Vuex 核心概念之 Action && mapActions

67 阅读2分钟

核心概念之 Action && mapActions

Action 类似于 mutation,不同在于:

  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。

让我们来注册一个简单的 action:

import Vue from 'vue'
import Vuex from 'vuex'
// 使用Vuex插件
Vue.use(Vuex)
const state = {
  count: 0
},
mutations: {
  increment(state){
    state.count++
  }
},
actions: {
  increment(context){
    context.commit('increment')
  },
  // 也可以通过解构
  increment({commit}){
    commit('increment')
  },
}

export default new Vuex.Store({
  actions: actions,
  mutations: mutations,
  state: state,
  getters: getters
})

Action函数接受一个与store实例具有相同方法和属性的context对象,因此你可以调用context.commit提交一个mutation,或者通过context.statecontext.getters来获取state和getters。在后面介绍Modules的时候,就知道context对象为什么不是store本身了

如何在组件中分发Action

Action 通过 store.dispatch 方法触发:

store.dispatch('increment')

为什么不直接分发mutation呢?因为mutaion必须是同步执行的,action则不受此约束,可以在action内部执行异步操作

actions: {
  incrementAsync ({ commit }) {
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
}

Actions 支持同样的载荷方式和对象方式进行分发:

// 以载荷形式分发
store.dispatch('incrementAsync', {
  amount: 10
})

// 以对象形式分发
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})

mapActions

组件中使用 this.$store.dispatch('xxx') 分发 action,也可以使用mapActions辅助函数将组件的methods映射为store.dispatch调用

<div @click="increment">increment</div>
<div @click="incrementBy">incrementBy</div>

import { mapActions } from 'vuex'
export default {
  // ...
  methods: {
    // 普通写法
    increment(){
      this.$store.dispatch('increment')
    },
    incrementBy(){
      this.$store.dispatch('incrementBy', 10)
    }
  
    ...mapActions([
      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

      // `mapActions` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
  }
}

组合 Action

Action通常是异步的,那么如何知道action什么时候结束,更重要我们如何才能组合多个action,以处理更加复杂的的异步流程呢

actions: {
  actionA({commit}) {
    return new Promise((resolve, reject)=>{
      setTimeout(()=>{
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}

现在你可以在组件里面:

this.$store.dispatch('actionA').then(()=>{
  //  
})

在另外一个 action 中也可以:

actions: {
  actionB({ dispatch, commit }){
    return dispatch('actionA').then(()=>{
      commit('someOtherMutation')
    })
  }
}

最后,如果我们利用 async / await,我们可以如下组合 action:

// 假设 getData() 和 getOtherData() 返回的是Promise

actions: {
  async actioA({commit}) {
    commit('gotData', await getData())
  },
  async actionB({dispatch, commit}) {
    await dispatch('actionA')
    commit('gotOtherData', await getOtherData())
  }
}

一个 store.dispatch 在不同模块中可以触发多个 action 函数。在这种情况下,只有当所有触发函数完成后,返回的 Promise 才会执行。