0
votes

In Vuex, what is the logic of having both "actions" and "mutations?"

I understand the logic of components not being able to modify state (which seems smart), but having both actions and mutations seems like you are writing one function to trigger another function, to then alter state.

What is the difference between "actions" and "mutations," how do they work together, and more so, I'm curious why the Vuex developers decided to do it this way?

I've tried .......

import Vuex from 'vuex'

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    INCREMENT (state) {
      // mutate state
      state.count++
    }
  }
})

Error code 502

3
Check out the documentation for actions. It even begins with "Actions are similar to mutations, the differences being that..."Phil
Error code 502 is a server-side error for "Bad Gateway". It's unlikely to have anything to do with your JS codePhil

3 Answers

1
votes
  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
votes

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
votes

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