3. Vuex – Mutation
Mutation
Mutation 用于变更 Store 中的状态
- 只能通过 mutation 变更 store 中的状态,不可以直接操作 store 中的状态
- 通过这种方式操作虽然很繁琐,但是可以监控状态的变化
- 无法执行异步操作
const store = new Vuex.Store({
state: {
状态名称:值,
...
},
mutations: {
事件名 (state, [参数...]) {
// 变更状态
state.状态名称
},
...
}
})
访问方式一
methods: {
// 触发 mutation
事件名 () {
this.$store.commit('事件名', [参数...])
}
}
访问方式二
// 1. 从 vuex 中按需导入 mapMutations 函数
import { mapMutations } from 'vuex'
// 2. 将指定的 mutations 函数,映射为当前组件的 methods 函数
methods: {
...mapMutations(['事件名', ...])
}