Action 類似于 mutation,不同在于:
* Action 提交的是 mutation,而不是直接變更狀態。
* Action 可以包含任意異步操作。
* 觸發Action 使用`store.dispatch()`
讓我們來注冊一個簡單的 action:
~~~
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
~~~
Action 函數接受一個與 store 實例具有相同方法和屬性的 context 對象,可以使用 context 對象提交commit,或者使用`context.state`和`context.getters`來獲取 state 和 getters。
> 注:context 對象不是 store 實例本身了
## **觸發 Action**
Action 通過`store.dispatch`方法觸發:
~~~
store.dispatch('increment')
~~~
~~~
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
~~~
Actions 支持同樣的載荷方式和對象方式進行分發:
~~~
// 以載荷形式分發
store.dispatch('incrementAsync', {
amount: 10
})
// 以對象形式分發
store.dispatch({
type: 'incrementAsync',
amount: 10
})
~~~
來看一個更加實際的購物車示例,涉及到**調用異步 API**和**分發多重 mutation**:
~~~
actions: {
checkout ({ commit, state }, products) {
// 把當前購物車的物品備份起來
const savedCartItems = [...state.cart.added]
// 發出結賬請求,然后樂觀地清空購物車
commit(types.CHECKOUT_REQUEST)
// 購物 API 接受一個成功回調和一個失敗回調
shop.buyProducts(
products,
// 成功操作
() => commit(types.CHECKOUT_SUCCESS),
// 失敗操作
() => commit(types.CHECKOUT_FAILURE, savedCartItems)
)
}
}
~~~
注意我們正在進行一系列的異步操作,并且通過提交 mutation 來記錄 action 產生狀態變更。
## **在組件中觸發Action**
你在組件中使用`this.$store.dispatch('xxx')`分發 action,或者使用`mapActions`輔助函數將組件的 methods 映射為`store.dispatch`調用(需要先在根節點注入`store`):
~~~
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**
Action 通常是異步的,那么如何知道 action 什么時候結束呢?更重要的是,我們如何才能組合多個 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(() => {
// ...
})
~~~
在另外一個 action 中也可以:
~~~
actions: {
// ...
actionB ({ dispatch, commit }) {
return dispatch('actionA').then(() => {
commit('someOtherMutation')
})
}
}
~~~
最后,如果我們利用[async / await](https://tc39.github.io/ecmascript-asyncawait/),我們可以如下組合 action:
~~~
// 假設 getData() 和 getOtherData() 返回的是 Promise
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}
~~~
> 一個`store.dispatch`在不同模塊中可以觸發多個 action 函數。在這種情況下,只有當所有觸發函數完成后,返回的 Promise 才會執行。