Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: {
//接受一个与 store 实例具有相同方法和属性的 context 对象 increment (context) { context.commit('increment') } }
//参数解构的简化写法
actions: { increment ({ commit }) { commit('increment') } }
//action内部支持异步
actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }
})
Action 通过 store.dispatch
方法触发
store.dispatch('increment')
// 以载荷形式分发 store.dispatch('incrementAsync', { amount: 10 }) // 以对象形式分发 store.dispatch({ type: 'incrementAsync', amount: 10 })
在组件中分发action
1,使用 this.$store.dispatch('xxx') 分发 action 2,使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用 import { mapActions } from 'vuex' export default { // ... methods: { ...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,以处理更加复杂的异步流程
store.dispatch
可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch
仍旧返回 Promise:
actions: { actionA ({ commit }) { return new Promise((resolve, reject) => { setTimeout(() => { commit('someMutation') resolve() }, 1000) }) } }
store.dispatch('actionA').then(() => { // ...在组件中使用dispatch })
actions: { // ..在另一个action中使用dispatch actionB ({ dispatch, commit }) { return dispatch('actionA').then(() => { commit('someOtherMutation') }) } }
//用 async / await //async直接返回一个promise对象,可以用then和cache来处理。
//sync异步函数遇到await会先返回一个Promise对象,等到异步操作执行完毕,才会根据结果来执行具体的回调函数
actions: { async actionA ({ commit }) { commit('gotData', await getData()) }, async actionB ({ dispatch, commit }) { await dispatch('actionA') // 等待 actionA 完成 commit('gotOtherData', await getOtherData()) } }