[Vuejs]-What is the difference between mutation and action

1👍

  1. Components should not change the state directly.
  2. So you’ve to trigger a ACTION from the component.
  3. In action, you’ll have the business logic like API call and It will trigger a call to MUTATION where the state updation happens.

1👍

Actions and mutations are similar in their behavior, so the differences are:

  • Actions can’t change your state directly, so they need to commit an operation to your mutations.
  • Think in actions like your functions.
  • Mutations are responsible for modify your state in Vuex store. To call a mutation you have to commit an action that call the mutation.

Example:

 actions: {
    MODIFY({dispatch, commit, getters, rootGetters}, obj) {
        //Do something
        commit('mymutation', obj)
    }
}

mutations: {
    mymutation(state, obj) {
        store.state.count = 1
    }
}

You can check more about mutations and actions at Vuex documentation

1👍

Mutations Must Be Synchronous so there is no way to change the state in async operation.

To solve this problem, vuex provides actions that change the state by commiting the synchronous mutations

If you have sync operation just use mutation, otherwise action + mutation

Leave a comment