Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
1. Action中调用 context.commit 提交 mutation
注册一个简单的 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 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。 但 context 对象并不是 store 实例本身,可查阅Modules。
我们会经常用到 ES2015 的 参数解构 来简化代码(特别是需要调用 commit 很多次的时候):
actions: {
increment ({ commit }) {
commit('increment')
}
}
2. store.dispatch触发Action
- Action 通过
store.dispatch方法触发:
store.dispatch('increment')
可能会感觉Action多此一举,我们直接分发 mutation 岂不更方便?实际上并非如此, mutation 必须同步执行,而Action 就不受约束!我们可以在 action 内部执行异步操作:
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
- Actions 支持同样的载荷方式和对象方式进行分发:
mutations: {
increment(state, amount) {
state.count += amount;
}
},
actions: {
incrementAsync({ commit }, { amount }) {
setTimeout(() => {
commit("increment", amount);
}, 1000);
}
}
// 以载荷形式分发
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 产生的副作用(即状态变更)。
3. 在组件中触发 Actionthis.$store.dispatch('xxx')
在组件中使用 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')`
})
}
}
4. 组合多个 Action
Action 通常是异步的,那么如何知道 action 什么时候结束呢?更重要的是,我们如何才能组合多个 action,以处理更加复杂的异步流程?
- 首先,
store.dispatch可以处理被触发的 action 的处理函数返回的 Promise,并且store.dispatch仍旧返回 Promise:
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation')
resolve("完成提交Mutation");
}, 1000)
})
}
}
- 现在可以触发Action:
store.dispatch('actionA').then((res) => {
// ...
console.log(res)
})
- 在另外一个 action 中也可以:
actions: {
// ...
actionB ({ dispatch, commit }) {
return dispatch('actionA').then(() => {
console.log("actionB完成提交someMutation");
commit('someOtherMutation')
})
}
}
- 最后,利用 async / await ,可以如下组合 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 才会执行。
5. 例子
<!DOCTYPE html>
<html>
<head>
<title>Vuex</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.8/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router@3.1.3/dist/vue-router.js"></script>
<script src="https://unpkg.com/vuex@3.0.0"></script>
</head>
<body>
<div id="app"></div>
<script>
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
someMutation(state) {
state.count++;
},
someOtherMutation(state) {
state.count++;
}
},
actions: {
actionA({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit("someMutation");
resolve("完成提交Mutation");
}, 1000);
});
},
actionB({ dispatch, commit }) {
return dispatch("actionA").then(() => {
console.log("actionB完成提交Mutation");
commit("someOtherMutation");
});
}
}
});
// 创建一个 Counter 组件
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count() {
// console.log("this.$store", this.$store);
return this.$store.state.count;
}
}
};
const router = new VueRouter({
routes: [
{
path: "/count",
component: Counter
}
]
});
const app = new Vue({
el: "#app",
router,
// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
store,
components: { Counter },
template: `
<div class="app">
<counter></counter>
</div>
`
});
</script>
</body>
</html>