在Vuex使用 以及 dispatch和commit来调用mutations的区别

时间:2023-12-24 19:40:07

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方法名',值)