mapMutations 是用来简化 methods 方法的一种写法,下面做一个对比:
- 未使用之前
methods: {
increment() {
this.$store.commit('increment')
}
},
- 使用mapMutations之后
methods: {
...Vuex.mapMutations([
'increment'
])
},
具体使用见下面代码详情
<!DOCTYPE html>
<html lang="en" xmlns="">
<head>
<meta charset="UTF-8">
<title>Vuex:mutation 的使用</title>
</head>
<body>
<div id="app">
<button-counter></button-counter>
</div>
<script src="vuex.js"></script>
<script src="vue.js"></script>
<script>
Vue.component('ButtonCounter', {
computed: {
count() {
return this.$store.state.count
}
},
methods: {
handleClick() {
alert('Hello, 我是组件自己的方法 ~')
},
...Vuex.mapMutations([
// 将 this.incrementBy(payload) 映射为 this.$store.commit('incrementBy', payload)
// 映射为 本地方法使用
'incrementBy'
]),
...Vuex.mapMutations({
// 将 this.add() 映射为 this.$store.commit('increment')
// 可以理解为 重命名
add: 'increment'
})
},
template: `
<div>
<button @click="handleClick">handleClick</button><hr>
<button @click="add">increment as add:You clicked me {{ count }} times.</button><hr>
<button @click="incrementBy({amount: 10})">incrementBy:You clicked me {{ count }} times.</button>
</div>
`
})
// 创建Vuex容器
const store = new Vuex.Store({
// 严格模式
strict: true,
// 状态数据放在 state 选项中
state: {
count: 0
},
// mutations 定义修改 state 选项中属性状态的方法,state 作为接收的第一次参数
// 不建议直接修改 state,直接修改不容易跟踪变化
mutations: {
increment(state) {
state.count++
},
// 支持额外参数,即 mutation 的 载荷(payload)
// payload 支持对象
incrementBy(state, payload) {
state.count += payload.amount
}
}
})
new Vue({
el: '#app',
store
});
</script>
</body>
</html>