1. What is Vuex?
Vuex is a state management model developed specifically for vuue.js applications (it uses centralized storage to manage the state of all components of the application and rules to ensure that the state changes in a predictable way).
You can think of vuEX as a development model or framework. For example, PHP has ThinkPHP, Java has Spring, etc., which centrally manages driver component changes through state (data source) (like Spring’s IOC container centrally manages beans).
2. Why Vuex
- Because multiple components depend on the same state, participation for multiple nested components can be cumbersome, and state transfer between sibling components cannot be done.
- And the behavior from different components needs to change the same state. Multiple copies of state that are referenced directly by parent components or changed and synchronized through events have been used in the past. These patterns are very fragile and often result in unmaintainable code.
- So we need to extract the shared state of the components and manage it in a global singleton. In this mode, our tree of components forms a giant “view” where any component can pick up state or trigger behavior no matter where in the tree.
- In addition, by defining and isolating concepts in state management and enforcing compliance with certain rules, our code becomes more structured and maintainable.
3. Core attributes of Vuex
3.1 state
Store data, store state; After the store is registered in the root instance, use this.$store.state to access the store. Corresponding to data in VUE; The vUE component reads data from the Store. If the data changes, the component will update accordingly.
3.2 getters
The return value of the store is cached according to its dependencies, and is recalculated only if its dependencies change. You can do something with the data in state.
3.3 mutation
The only way to change the state in Vuex’s store is to submit mutation, which is submitted to the Mutations module via store.mit
3.4 action
Actions is a method to change the state in state asynchronously, submitting to the Mutations module via store.dispatch, and submitting commit to change the state in state
3.5 modules
Vuex allows us to split the Store into modules. Each module has its own state, mutation, action, getter, and even nested submodules — split the same way from top to bottom
For more details, check out this blog post