四、Vuex - Mutation

Mutation 更改 state 的唯一方式

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。
每个 mutation 都有一个字符串的事件类型(type)和一个回调函数(handler), 这个回调函数就是实际进行状态更改的地方, 接收 state 作为第一个参数.
通过 store.commit 提交 mutation 事件类型, 触发对应的回调函数.

** mutation 需遵守 Vue 的响应规则**

  1. 最好提前在你的 store 中初始化好室友所需属性
  2. 当需要在对象上添加新属性时, 应该使用一下方式:
// 使用 Vue.set
Vue.set(obj, "newProp", 123);

// 以新对象替换老对象
state.obj = { ...state.obj, newProp: 123 };

定义 mutation 事件

const store = new Vuex.Store({
    state: {
        count: 1
    },
    mutations: {
        increment (state) {
            state.count++; // 更改状态
        },
        getCount (state, payload) {
            state.count += payload;
        }
    }
});

提交 mutation

通过 store.commit 来提交 mutation 改变状态

// 普通提交方式
this.$store.commit("increment");

// 提交 mutation 并传参, 只能传一个参数(类型不限)
this.$store.commit("getCount", 10);

// 以对象的形式提交
this.$store.commit({
    type: "getCount",
    num: 10
});

使用常亮替代 Mutation 事件类型

// mutation-type.js
export const SOME_MUTATION = "some_mutation";

// store.js
import Vuex from 'vuex';
import { SOME_MUTATION } from './mutation-type';

const store = new Vuex.Store({
    state: {},
    mutations: {
        // 使用ES2015 风格的计算属性命名功能来使用一个常量作为函数名
        [SOME_MUTATION] (state) {}
    }
});

使用 mapMutations 辅助函数

import { mapMutations } from 'vuex';

export default {
    methods: {
        // 以数组的形式
        ...mapMutations([
            // 将 this.increment() 映射为 this.$store.commit('increment')
            'increment',
            // 将 this.incrementBy(num) 映射为 this.$store.commit('incrementBy', num)
            'incrementBy'
        ]),
        ...mapMutations({
            // 将 this.add() 映射为 this.$store.commit('increment')
            add: 'increment'
        })
    }
}

猜你喜欢

转载自www.cnblogs.com/yuxi2018/p/11966801.html