vuex中 this.$store.dispatch() 与 this.$store.commit()方法的区别

dispatch:含有异步操作,例如向后台提交数据,写法: this.$store.dispatch('action方法名',值)
commit:同步操作,写法:this.$store.commit('mutations方法名',值)
1. 在Vue组件中提交 mutation

\src\store\index.js

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);

// Vuex 的状态存储是响应式的

// 创建一个Vuex.Store的实例
const store = new Vuex.Store({

  // 存储状态
  state: {
    count: 0
  },

  // mutation中最多有两个参数,第一个参数为state,要传多个参数,可传递一个对象
  mutations: {
    // 类型为 increment 的 mutation
    increment (state) {
      // 变更状态
      state.count++;
    },
    // 类型为 reduce 的 mutation
    reduce (state, n) {
      // 变更状态
      state.count -= n;
    },
    // 类型为 change 的 mutation,第二个参数为一个对象
    change (state, payload) {
      // 变更状态
      state.count = state.count + payload.a + payload.b;
    }
  }
});

export default store;

routertest\testState.vue




效果:

vuex中 this.$store.dispatch() 与 this.$store.commit()方法的区别_第1张图片

2. 对象风格提交mutation

提交 mutation 的另一种方式是直接使用包含 type 属性的对象
当使用对象风格的提交方式,整个对象都作为载荷传给 mutation 函数



 

 3. 展开运算符+mapMutations辅助函数(...mapMutations)


 

4. Action 异步变更状态

// 创建一个Vuex.Store的实例
const store = new Vuex.Store({
 
  state: {
    count: 0
  },
 
  mutations: {
    increment (state) {
      state.count++;
    }
  },
 
  // 异步变更状态,Action 提交的也是 mutation
  // Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象
  // Action调用 context.commit 提交一个 mutation
  // Action通过 context.state 和 context.getters 获取 state 和 getters。
  actions: {
    increment (context) {
      context.commit('increment');
    }
  }
});

在组件中使用actions,在组件中使用actions和在组建中使用mutations类似区别就是,mutations使用this.$store.commit('mutation方法名')提交mutation;actions使用this.$store.dispatch('action方法名')分发action



5. 展开运算符+mapActions 辅助函数(...mapActions )



你可能感兴趣的:(Vue,vue.js,javascript,npm)