可以在触发mutations时传递参数
import { mapState, mapMutations } from 'vuex'
//state仓库本身,step外界传进的参数
addN(state, step) {
state.count += step
}
<button @click="btnHandler2">+N</button>
btnHandler2() {
// commit的作用就是调用某个mutation函数
this.$store.commit('addN', 3)
},
this.$store.commit()是触发mutations的第一种方式
触发mutations的第二种方式:
1.从vuex中按需导入mapMutations函数
import { mapMutations } from 'vuex';
通过导入的mapMutations函数,将需要的mutations函数,映射为当前组件的methods方法:
2.将指定的mutations函数,映射为当前组件的methods函数
methods:{
...mapMutations(['add','addN']);
}
import { mapState, mapMutations } from 'vuex'
methods: {
...mapMutations(['sub']),
btnHandler1() {
this.sub()
},
},
sub(state){
state.count--;
}
<button @click="btnHandler1">-1</button>
<button @click="btnHandler1">-1</button>
<button @click="btnHandler2">-N</button>
import { mapState, mapMutations } from 'vuex'
methods: {
...mapMutations(['sub', 'subN']),
btnHandler1() {
this.sub()
},
btnHandler2() {
this.subN(3)
},
},
sub(state) {
state.count--
},
subN(state, step) {
state.count -= step
}