The only way to change the state of Mutation
The only way to change Vuex the store is in a state of submission mutation.
Event type (type) of each mutation has a string and a callback function (handler), the callback function is actually where the state changes, the receiving state as the first argument.
Submit mutation event types by store.commit, triggers the corresponding callback function.
** mutation subject to the rules in response to the Vue **
- Ahead of the best in your store attributes required to initialize a good roommate
- When you need to add a new property on an object, you should use the method:
// 使用 Vue.set
Vue.set(obj, "newProp", 123);
// 以新对象替换老对象
state.obj = { ...state.obj, newProp: 123 };
The definition of mutation events
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
state.count++; // 更改状态
},
getCount (state, payload) {
state.count += payload;
}
}
});
Submit mutation
To submit mutation changes state by store.commit
// 普通提交方式
this.$store.commit("increment");
// 提交 mutation 并传参, 只能传一个参数(类型不限)
this.$store.commit("getCount", 10);
// 以对象的形式提交
this.$store.commit({
type: "getCount",
num: 10
});
Always use an alternative type of event 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) {}
}
});
Use mapMutations Helper
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'
})
}
}