vuex深入学习 — Action
特性:
-
Action 提交的是 mutation,而不是直接变更状态。
-
Action 可以包含任意异步操作
-
适合多个Mutation的操作
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
// 这里 context 可以使用对象解构 {commit}
increment (context) {
context.commit(‘increment’)
}
}
})
调用: this.$store.dispatch('increment')
载荷形式: this.$store.dispatch('incrementAsync', {amount: 10})
对象形式: this.$store.dispatch({type: 'incrementAsync',amount: 10})
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象
因此可以调用 context.commit 提交一个 mutation
或者通过 context.state
和 context.getters
来获取 state 和 getters
1.mapActions 辅助函数
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({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}
}
2.组合Action
store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise
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())
}
}