vuex深入学习 — Mutation
特点:
-
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。
-
Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。
-
这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数,但handler不能直接调用
-
mutation必须是同步函数,适合多个state的操作,mutation是不分组件的,当调用mutation中的方法时,会调用说有组件中的同名方法
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
} })
调用: this.$store.commit('increment')
1.提交载荷(Payload)
你可以向 store.commit 传入额外的参数,即 mutation 的 载荷(payload)
mutations: {
increment (state, n) {
state.count += n
}
}
直接传参: this.$store.commit('increment', 10)
对象传参: this.$store.commit('increment', {amout: 10, uname: 'tom'})
对象调用:
this.$store.commit({
type: 'increment',
amout: 10
})
注意:
-
最好提前在你的 store 中初始化好所有所需属性。
-
当需要在对象上添加新属性时,你应该使用 Vue.set(obj, ‘newProp’, 123)
或者以新对象替换老对象 state.obj = { …state.obj, newProp: 123 } -
使用常量替代 Mutation 事件类型
// mutation-types.js export const SOME_MUTATION = 'SOME_MUTATION' // store.js import Vuex from 'vuex' import { SOME_MUTATION } from './mutation-types' const store = new Vuex.Store({ state: { ... }, mutations: { // 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名 [SOME_MUTATION] (state) { // mutate state } } })