What is Vuex
Vuex is a state management mode developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of an application and rules to ensure that the state changes in a predictable way
Why decide when to use Vuex
It’s simple. You can’t use Vuex all the time. Lu Xun says: — When you can’t manage data well, you need Vuex
However, how to determine using application scenarios?
I have written and launched at least four or five projects using Vue + Vuex. Here are some of my personal judgments about how to use scenarios
1. When a component needs to dispatch events more than once
Why? Vuex is required for multiple dispatch events? The reason is simple: if it dispatches events multiple times, some other component must receive and invoke them. It’s fine if it’s one component that receives and calls, but if it’s two? Three? Or even four? If the component that dispatches events only dispatches one event, it is easier to manage, and the difficulty of maintenance multiplies once dispatches multiple times
Chestnut:
On the other hand, if the interface to get the number of shopping carts is called every time (if there is one), the effect is achieved, but each HTTP request is a drain on browser performance. In contrast, triggered by Vuex mutations, it appears to have more advantages
The following scenario diagram corresponds to the trigger
After all: for the convenience of maintenance, you think about it. In case you change it that day, there are four or five other things you need to change. As the program gets bigger, more and more places will join in. Keep a set number of carts, so that no matter how many cases you have, you can clearly see that there is a set number of carts and you need to change it where do you change it
2. Share data across components and pages
This has been discovered many times during the development of the Vue project. The existence of this case encapsulates a basic component (which is used in many places) that distributes different events based on the business that is not in use. Sometimes, however, it is not possible to distribute events because the parent component has no reference at all. No reference to the parent component and get the current dispatch event and update the data? Vuex, of course
Chestnut:
Click the cancel button to update the corresponding order list. Don’t say that every time you go to the order list page, it’s a waste of performance. In this case, Vuex state stores a state, listens for that state, and updates the list as it changes
Chestnut:
Of course, there are more than two. But most of the time.
Why? I’m not going to write down the other cases. It’s just that I don’t remember it for a second, and I don’t want to write it. And when you do those two things, I think, you know, everybody can relate.