Mutation用于变更store中的数据
1 只能通过mutation变更store数据 不可以直接操作store中的数据
2 通过这种方式虽然操作起来稍微繁琐一些 但是可以集中监听所有数据的变化
第一种方式 commit
在 store/index.js 中定义
// 定义 Mutation
const store = new Vuex.Store({
state: {
count:0
},
mutations: {
sub (state) {
state.count--
}
}
})
在使用的页面触发
// 触发mutation
methods: {
handleBtnSub(){
// 触发mutation的第一种方式
this.$store.commit('sub')
}
}
commit 的作用 就是调用 某个mutation函数
触发 mutations 时传递参数
mutations:{
subN (state, step) {
state.count -= step
}
}
methods:{
handleBtnSub(){
this.$store.commit('subN',3)
}
}
触发mutation的第二种方式 mapMutations
// 从vuex中按需导入 mapMutations 函数
import {mapMutations} from 'vuex
// 通过导入的函数 将需要的mutations函数 映射为当前组件的methods方法
methods:{
...mapMutations(['sub', 'subN']),
handleBtnSub () {
this.sub()
},
handleBtnSubN () {
this.subN(3)
}
}
// @click="handleBtnSub"这里相当于另起一个方法调用 也可以直接 @click="sub"
不要在 mutations 函数中执行异步操作
Action 用于处理异步任务 前往:Action的基本使用