一,前言
上一篇在介绍mutation时,提到了mutation中必须是同步函数
这篇就来介绍Vuex-核心概念-Action,Action用来处理异步操作
二,Vuex-Action
Action和mutation很相似,两者的区别在于:
Action提交的是mutation,而不是直接变更状态
Action可以包含任意异步操作
三,Action的使用
注册一个简单的 action:
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
// 注册action
actions: {
increment (context) {
context.commit('increment')
}
}
})
Action函数接受一个与store实例具有相同方法和属性的context对象,(context对象并不是store 实例本身)
因此可调用context.commit提交一个mutation
(还可以通过context.state和context.getters来获取state和getters)
使用ES2015参数解构来简化代码:
actions: {
increment ({ commit }) {
commit('increment')
}
}
四,分发Action
Action通过store.dispatch方法触发:
store.dispatch('increment')
由于mutation必须同步执行,这时,可在action内部执行异步操作,
当异步才做完成时,再提交mutation
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)
)
}
}
五,mapActions辅助函数
在组件中使用this.$store.dispatch('xxx')分发action,
还可以使用mapActions辅助函数将组件的methods映射为store.dispatch调用(需要先在根节点注入 store):
import { mapActions } from 'vuex'
export default {
// ...
methods: {
...mapActions([
// 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
'increment',
// `mapActions` 也支持载荷:
// 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
'incrementBy'
]),
...mapActions({
// 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
add: '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,进行如下组合:
// 假设 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才会执行
七,结尾
下一篇介绍Vuex最后一个核心概念Module