# Vuex 文档初探(四): Mutation

mutation用于改变store里的状态:

# 基本用法

// store.js
const store = new Vue.Store({
  state: {
    count: 1
  },
  mutations: {
    increment: state => state.count++
  }
});

// main.js
store.commit("increment");
1
2
3
4
5
6
7
8
9
10
11
12

# payload

// store.js
mutations: {
  increment: (state, payload) => (state.count += payload.n);
}

// main.js
store.commit("increment", { n: 10 });
1
2
3
4
5
6
7

# 使用常量代替事件类型

当项目过大时, 我们可以把事件类型以常量代替, 再将这些常量放在单独的文件里:

// mutation-types.js
export const INCREMENT = "increment";
export const DECREMENT = "decrement";

// store.js
import { INCREMENT, DECREMENT } from "./mutation-types";
const store = new Vue.Store({
  state: {},
  mutations: {
    [INCREMENT](state) {},
    [DECREMENT](state) {}
  }
});
1
2
3
4
5
6
7
8
9
10
11
12
13

WARNING

Mutation 必须是同步函数

# mapMutation

import { mapMutations } from "vuex";

export default {
  // ...
  methods: {
    ...mapMutations([
      "increment", // 将 `this.increment()` 映射为 `this.$store.commit('increment')`

      // `mapMutations` 也支持载荷:
      "incrementBy" // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
      add: "increment" // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
  }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16