Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
952 views
in Technique[技术] by (71.8m points)

vue.js - Vuex Action vs Mutations

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 ({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:

  • 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...