vuex中commit与dispatch的区别

 

this.$store.commit("increment")调用的是vuex中mutation中的increment函数,而this.$store.dispatch("increment")调用的是vuex中actions中的increment函数,mutation有同步限制,就是说mutation中不能执行异步操作,否则vuex无法识别什么时候修改state,state修改就会失败;actions中可以调用mutation中的函数,也可以执行异步操作,所以有异步操作要在actions中写代码,然后在执行commit方法调用mutation中的函数修改state;如果把actions中的increment命名改成incrementAction的话,在调用this.$store.dispatch("increment")就会报错,告诉你找不到该方法,应该调用this.$store.dispatch("incrementAction")


 

commit: 同步操作
存储

1
this.$store.commit('changeValue',name)

取值

1
this.$store.state.changeValue

 

dispatch: 异步操作
存储

1
this.$store.dispatch('getlists',name)

取值

1
this.$store.getters.getlists
posted @ 2022-03-17 15:55  踏浪小鲨鱼  阅读(330)  评论(0)    收藏  举报