前言
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
//increment 事件类型 (type)
//(state) {
// 变更状态
//state.count++
//}一个 回调函数 (handler)
increment (state) {
// 变更状态
state.count++
}
}
})
提交载荷(Payload)
this.$store.commit('increment', 10)
mutations: {
increment (state, n) {
state.count += n
}
}
在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读
this.$store.commit('increment', {
amount: 10
})
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
对象风格的提交方式
提交 mutation 的另一种方式是直接使用包含 type 属性的对象:
this.$store.commit({
type: 'increment',
amount: 10
})
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
mapMutations 辅助函数
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')`
})
}
}