Vuex之Action
Action 类似于 mutation,不同在于:
1. Action 提交的是 mutation,而不是直接变更状态。
2. Action 可以包含任意异步操作。
用Action处理异步操作示例:
// 正常的mutation const increment = (state) => { state.count++ } const decrement = (state) => { state.count-- } export {increment, decrement}
// action.js处理一些异步操作 // Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象 let incrementAsync = (context) => { setTimeout(() => { context.commit('increment') }, 1000) } let decrementAsync = (context) => { setTimeout(() => { context.commit('decrement') }, 1000) } export {incrementAsync, decrementAsync}
<template>
<div>
<button @click="decrementAsync">-</button>
<span>{{count}}</span>
<button @click="incrementAsync">+</button>
</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex'
export default {
computed: {
...mapState(['count'])
},
methods: {
...mapMutations(['increment', 'decrement']),
...mapActions(['incrementAsync', 'decrementAsync']) //这里用了辅助函数,不了解的可以看这个系列的第二篇文章
}
}
</script>
Action 通过store.dispatch方法分发:
// 以载荷形式分发 store.dispatch('incrementAsync', { amount: 10 }) // 以对象形式分发 store.dispatch({ type: 'incrementAsync', amount: 10 })

浙公网安备 33010602011771号