Vuex Action vs Mutations

前端 未结 13 1091
囚心锁ツ
囚心锁ツ 2020-12-02 04:37

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

13条回答
  •  死守一世寂寞
    2020-12-02 05:10

    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)

提交回复
热议问题