更改store中状态的唯一方法就是提交mutation
每个 mutation 都有一个字符串的事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数;
mutation的回调函数不能直接调用,必须要用对应type调用store.commit方法 store.commit('increment')
mutation的载荷即除state外的参数,多为对象

mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}
store.commit('increment', {
  amount: 10
})

mutation提交的另一种方式,直接使用包含type属性的对象,但不影响mutation中回调函数

store.commit({
  type: 'increment',
  amount: 10
})

使用常量替代 mutation 事件类型,同时把这些常量放在单独的文件中(多人协作常用!!!)

// mutation-types.js 
export const SOME_MUTATION = 'SOME_MUTATION'    // 定义常量

// store.js
import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'   //引入常量

const store = new Vuex.Store({
  state: { ... },
  mutations: {
    [SOME_MUTATION] (state) {  //使用
      // mutate state
    }
  }
})

Mutation 必须是同步函数

在组件中使用 this.$store.commit(‘mutation类型’) 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)

import { mapMutations } from 'vuex'

export default {

  methods: {
    ...mapMutations([
      'increment',  // 将 `this.increment()` 映射为 `this.$store.commit('increment')`

      // `mapMutations` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
  }
}
Logo

前往低代码交流专区

更多推荐