Mutation
Mutation 用于改变Store中的数据。
- 只能通过mutation变更Store数据,不可以直接操作Store中的数据。
- 通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。
//定义 Mutation
const store = new Vuex.Store({
state:{
count:0;
},
mutations:{
add(state){
//变更状态
state.count++
}
}
})
//触发mutation
methods: {
handle1(){
//触发mutations的第一种方式
//commit 的作用就是调用mutations中的某个函数
this.$store.commit('add')
}
}
可以在触发mutations时传递参数:
const store = new Vuex.Store({
store:{
count :0;
},
mutations:{
addN(state,step){
//变更状态
state.count += step
}
}
})
//触发mutation
methods:{
handle2 (){
//在调用commit函数,
//触发mutations时携带参数
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']),
btnHandle1(){
this.add()
},
btnHandle2(){
this.addN(3)
}
}
注意:不要在mutations函数中,执行异步操作,下面是错误写法:
mutations:{
add(state){
setTimeout(()=>{
state.count++;
},1000);
}