Question 1: Why did the Vuejs developers decide to do it this way?
Answer:
- When your application becomes large, and when there are multiple developers working on this project, you will find that “state management” (especially the “global state”) becomes increasingly more complicated.
- 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 ({commit}) { commit('INCREMENT') } // a action with additional arguments // with ES2015 argument destructuring function incrementBy ({ dispatch }, amount) { dispatch('INCREMENT', amount) }
Here is my explanation of the above:
- A mutation is the only way to modify state
- The mutation doesn’t care about business logic, it just cares about “state”
- An action is business logic
- The action can commit more than 1 mutation at a time, it just implements the business logic, it doesn’t care about data changing (which is managed by mutation)