VueX understanding and use

(1) Definition:

Vuex is a state management pattern specially developed for vue.js applications

Usage scenarios: (1) login information, (2) shopping cart, (3) complex component communication

(2) Advantages of using Vuex

  • 1. The state between multi-layer nested components and sibling components will be better managed and maintained.
  • 2. Cache some remote or local data sets that are currently required to be used (it will be destroyed by itself after refreshing).
  • 3. With the second article, you can reduce the requests to the server and save resources. If you have enough users, every additional request is a lot of money for the company.
  • 4. For developers, if your project is complex enough and the team size is not limited to one person, centralized data processing is more conducive to the stability and maintenance of the program.

(3) Core concepts

Five core concepts of Vuex: state, getters, mutations, actions, modules

1. state: the basic data of vuex, used to store variables ;

2. Getters: Data derived from the basic data (state), which is equivalent to the calculated property of the state ;

3. mutations: The method for submitting updated data must be synchronous (if asynchronous, you need to use action). Each mutation has a string event type (type) and a callback function (handler).

The callback function is where we actually make the state change, and it accepts the state as the first parameter and the submitted payload as the second parameter.

4. action: has roughly the same function as mutation, the difference is that

①Action submits a mutation instead of directly changing the state

②Action can contain any asynchronous operation.

5. Modules: Modular vuex allows each module to have its own state, mutation, action, and getters, making the structure very clear and easy to manage.

Implementation steps

* dispatch triggers action ->commit triggers mutation -> state

example:

// call the function in the mutation

    this.$store.commit('function name', data);

// Call the function in actions

    this.$store.dispatch('function name'); dispatch=>send, dispatch

Guess you like

Origin blog.csdn.net/weixin_50543490/article/details/127992940