Sobes.tech
Middle

Tell us about mutations in Vuex.

sobes.tech AI

Answer from AI

Mutations in Vuex are the only way to change the store's state. They are synchronous and accept the state (state) as the first argument. The second argument can be a payload object.

They are defined in the mutations object of the module or root store. They are called using the commit method.

// Defining a mutation
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++ // Changing state
    },
    incrementBy (state, payload) {
      state.count += payload.amount // Changing state with payload
    }
  }
})

// Calling a mutation
store.commit('increment')
store.commit('incrementBy', { amount: 10 })

Key points:

  • Synchronous: All mutations are executed synchronously, ensuring predictable state changes.
  • Only way: Only mutations can directly change the store's state.
  • commit: Mutations are invoked using the store.commit() method.
  • Payload: A mutation can accept a second argument - payload, containing additional data.
  • Tracking: Vuex Devtools track all mutations, simplifying debugging.

Differences from actions:

  • Synchronous vs Asynchronous: Mutations are synchronous, actions can contain asynchronous operations.
  • Direct state change vs Committing mutations: Mutations directly change the state, actions commit mutations.
Characteristic Mutations Actions
Synchronous Synchronous Can be asynchronous
State change Change state directly Commit mutations
Call store.commit() store.dispatch()
Purpose Record state Business logic, async operations