不能在mutation的函数中执行异步操作,因为如果在这里面进行异步操作,虽然页面发生改变,但是vuetool这个工具中数据没有发生改变。
action用于处理异步任务,通过触发mutation中的函数间接更新state的数据
1.触发Actions的第一种方式
1.1首先在store的Action中定义一个事件,将异步任务放入其中,事件中第一个参数context,通过commit进行进行调用,可以拿到mutation中的事件,通过修改mutation中的事件来改变state。
state: {count:0},mutations: {add(state,num){state.count++}},actions: {addAsync(context){setTimeout(()=>{context.commit("add")},1000)}},
1.2在组件中通过this.$store.dispatch来调用异步事件
methods: {handleAddClick(){this.$store.dispatch("addAsync")}},
2.触发Actions异步任务携带参数第一种方式
2.1在组件中将参数传递进去,第二个参数就是从外界传递进入的参数
methods: {handleAddClick(){this.$store.dispatch("addAsync",3)}},
2.2在store中进行action中定义一个事件,第二个参数与上面的对应,通过context.commit(“add”,num1),将该参数传递到mutation中,这里的参数是num1,在mutations这种去接受这个外界传来的参数
export default new Vuex.Store({state: {count:0},mutations: {add(state,num1){state.count+=num1},reduce(state,num1){state.count-=num1}},actions: {addAsync(context,num1){setTimeout(()=>{context.commit("add",num1)},1000)}},
3.触发Action的第二种方式
3.1首先在组件导入该vuex的mapActions函数
import {mapActions} from "vuex"
3.2在methods中把对应的mapActions函数映射过来
methods: {...mapActions(['reduceASync']),redudceClick(){this.reduceASync()}},
4.触发Actions异步任务携带参数第二种方式
组件中
methods: {...mapActions(['reduceASync']),redudceClick(){//这里传过去一个3this.reduceASync(3)}},
在store中,这里的num2对应传递过来的3
export default new Vuex.Store({state: {count:0},mutations: {reduce(state,num2){state.count-=num2}},actions: {reduceASync(context,num2){setTimeout(()=>{context.commit("reduce",num2)},1000)}},})
