在Vuex使用dispatch和commit来调用mutations的区别详解
main.js中
import Vuex from 'vuex' Vue.use(vuex); const store = new Vuex.store({ state: { nickName: "", cartCount: 0 }, mutations: { updateUserInfo(state,nickName) { state.nickName = nickName; }, updateCartCount(state,cartCount) { state.cartCount += cartCount; } }, actions: { updateUserInfo(context) { context.commit("updateUserInfo"); }, updateCartCount(context) { context.commit("updateCartCount"); } } }) new Vue({ el: "#app", store, router, template: '<App/>', components: {App} })
组件中:
methods: { increment(){ this.$store.dispatch("updateUserInfo", 'nick'); //this.$store.commit("increment", 'nick'); }, decrement() { this.$store.dispatch("updateCartCount", 1); // this.$store.commit("decrement", 1); } }
区别:
dispatch:含有异步操作,例如向后台提交数据,写法: this.$store.dispatch('mutations方法名',值)
commit:同步操作,写法:this.$store.commit('mutations方法名',值)
相关推荐
CSCCockroach 2020-09-15
lbPro0 2020-07-05
MrSunOcean 2020-06-21
lylwanan 2020-06-14
Callmesmallpure 2020-05-31
ShaLiWa 2020-05-25
墨龙吟 2020-04-24
MrSunOcean 2020-04-24
H女王范儿 2020-04-22
lbPro0 2020-04-16
ShaLiWa 2020-02-29
ShaLiWa 2020-01-17
MrSunOcean 2020-01-03
lbPro0 2020-01-01
H女王范儿 2019-12-29