Vuex Action vs Mutations

Kobi picture Kobi · Sep 2, 2016 · Viewed 49.9k times · Source

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 moreso, I'm curious why the Vuex developers decided to do it this way?

Answer

Kaicui picture Kaicui · Sep 3, 2016

Question 1: Why the Vuejs developers decided to do it this way?

Answer:

  1. When your application becomes large, and when there are multiple developers working on this project, you will find the "state manage" (especially the "global state"), will become increasingly more complicated.
  2. The vuex way (just like Redux in react.js) offers a new mechanism to manage state, keep state, and "save and trackable" (that means every action which modifies state can be tracked by debug tool:vue-devtools)

Question 2: What's the difference between "action" and "mutation"?

Let's see the official explanation first:

Mutations:

Vuex mutations are essentially events: each mutation has a name and a handler.

import Vuex from 'vuex'

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

Actions: Actions are just functions that dispatch mutations.

// the simplest action
function increment (store) {
  store.dispatch('INCREMENT')
}

// a action with additional arguments
// with ES2015 argument destructuring
function incrementBy ({ dispatch }, amount) {
  dispatch('INCREMENT', amount)
}

Here is my explanation of the above:

  • mutation is the only way to modify state
  • mutation doesn't care about business logic, it just cares about "state"
  • action is business logic
  • action can commit more than 1 mutation at a time, it just implements the business logic, it doesn't care about data changing (which manage by mutation)