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?
Question 1: Why the Vuejs developers decided to do it this way?
Answer:
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: