vuex 异步调用触发actions
如果通过异步操作变更数据,必须通过actions,而不能直接使用mutations,但是在actions还是要通过触发mutations来间接改变state。
组件页面派发(dispatch)一个actions,actions提交一个mutations,数据发生改变
代码如下
store.js代码
state: {
count: 0
},
mutations: {
add(state, step) {
state.count += step
}
},
actions: {
asycAdd(context, step) {
setTimeout(() => {
context.commit('add', step)
}, 2000)
}
},
组件页面代码
<template>
<div class="echart">
<h1>{{count}}</h1>
<button @click="addHandel">+1</button>
<button @click="addHandelAsync">+1Async</button>
<!-- 直接映射过来的方法 -->
<button @click="asycAdd(10)">+1Async</button>
</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex'
import store from '../../../store'
export default {
data() {
return {
}
},
computed: {
...mapState(['count'])
},
methods: {
...mapMutations(['add']),
// 也可以直接把映射过来的方法直接写在标签的点击方法中,不用在定义一个方法名
...mapActions(['asycAdd']),
// 第一种触发actions的方法
addHandel() {
this.$store.dispatch('asycAdd', 10)
},
// 第二种触发actions的方法
addHandelAsync(){
this.asycAdd(10)
}
}
}
</script>
<style scoped>
</style>