[Vue] Working principle of vuex

  1. At the beginning, write and call an api  in the component : dispatch('jia',2)  , pass in a key and a parameter 2
  2. Then to the Actions actions as an object, call the api: commit('jia',2)

  3. Then in the mutation, the mutation is also an object with a method, write in the corresponding method, a method, this method contains the state and the incoming value, as long as you write state.sum+=2 in this method, it is equivalent to realizing mutate operation.

  4. Then go to the state, the state is an object, and there are shared variables in it, and the corresponding data in it is modified.

  5. Finally, re-analyze the component and update the data.

And the actions here can accept the return value of sending Ajax request

And if you know the data to be operated on, that is, when the data is available in the component, you can skip actions and go directly to mutations

Example:

To illustrate with an example of going to a restaurant to eat

The component is equivalent to the customer. When you arrive at the restaurant, you call the waiter and order two servings of egg fried rice (egg fried rice is equivalent to the data type, and 2 is equivalent to the transmitted data): dispath('jia',2)

Then the waiter (actions) will help you order through the app, fill in the content that you want two fried rice with eggs, tell the kitchen that you need two fried rice with eggs: commit('jia',2)

Then the back kitchen (mutations) knows that two servings of egg fried rice are needed, so they make it (equivalent to processing our data : state.sum+=2)

Then the dish (state) is finished and passed (render) to the guests

And if the customer is very familiar with the chef, there is no need for a waiter, and the chef can directly tell the chef what dish to eat, which is equivalent to saving the actions

But if the customer enters the store to order food and finds that the dishes have been changed, then the waiter must be required to order for you at this time, and this is equivalent to sending Ajax through actions when your data is on another server Request to get the corresponding data

And the waiter can also remind you when you order two dishes and the two dishes cannot be eaten together. Logical judgments need to be written in actions.

And these three actions mutations state must be managed by a store warehouse

store is indispensable, because all these apis need store

即 store.dispath,store.commit

Guess you like

Origin blog.csdn.net/qq_37308779/article/details/125903917