mian.js中:这样写 下面引入一下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方法名',值)
Logo

前往低代码交流专区

更多推荐