preface
Before learning Vuex, the most common way to pass values to sibling components was to use the third component (EventBus) or parent component, which is more friendly for small projects, but more troublesome for enterprise projects or larger projects. And in Vue official documents, provides a way of state management Vuex, which constitutes an important part of Vue ecology. Vuex is a great tool for managing data on large, complex projects in a clear and organized way, making the flow of data controllable and traceable across every component and module.
1 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 manner.
Personal understanding: Vuex is the warehouse administrator, responsible for the unified management of each category of goods (data), to achieve classification, quick search and access and other functions, to truly manage data like commodities. Which area needs the corresponding goods will be delivered to the past, the goods in the corresponding warehouse will be changed accordingly. The Vuex warehouse can realize the management of global state data and the sharing of data between components easily and quickly.
So, what are the benefits of using ‘Vuex’ for unified management of data state?
- In the
Vuex
To centrally manage shared data, facilitating development and subsequent maintenance - It can realize data sharing and communication between components efficiently and improve development efficiency
- Stored in the
Vuex
The data in is responsive, keeping the data in sync with the page in real time
It has been said that ‘Vuex’ is a mode for data state management, so what kind of data is suitable for storing in ‘Vuex’?
In terms of actual development, the average small project can do well without Vuex data management. For large enterprise projects, Vuex can be adopted to manage the global data shared between components, while private data in components is still stored in the data of components for processing.
2 What is state management mode?
The official document mentions the term “state management mode”, so what exactly is “state management mode”? If you want to know, follow my lead and take you with me.
The brief version of the state management model includes three parts: State, View and Actions.
state
Equivalent to the componentdata
Which is responsible for storing global data (i.e., the warehouse) and driving the data source of the application.view
Is the data to be rendered to display the view page, can bestate
The data is mapped to the page.actions
As the literal meaning of action, change, to inview
In response to data changes made on the.
The figure below is a schematic diagram of a simple “unidirectional data flow” model. It seems to be a stable triangular structure, but in fact its data flow is not stable at all. When multiple components share data in this “unidirectional data flow” model, we need to consider that multiple views depend on the same data state at the same time, and that behaviors from multiple different views need to change the same data state.
We know that in the past, component passvalues are passed through hierarchical nesting, which leads to the same as the layer cake, layer on layer, and there is nothing to do with the sibling component passvalues. In the face of the update and synchronization of the data state, the method is often directly referenced by the parent and child components or the form of event driven. This method is complicated to operate and difficult to maintain.
The implementation principle of Vuex is to extract the shared state data of components into the warehouse and trigger the data to be rendered on the view with a global “state management mode”. The global components are built into a huge view tree, and the data is like the trunk, can pass the data flow to each view cotyledon, any component can obtain the state or trigger the behavior!
We can go down hereVuex
As can be seen from the composition diagram of:
State
Is as a data management warehouse, data storage container.Getter
Equivalent to the componentComputed
Properties,getter
The return value of is cached based on the dependency and is recalculated for use when the dependency value changes.Mutation
Is for updatingstore
In thestate
The only method of data state that corresponds to themethods
, but it cannot perform operations on asynchronous methods (timers, axios asynchronous requests, and so on).Actions
In fact, andMutation
It does the same thing, exceptActions
isVuex
Used specifically to handle asynchronous methods, by operationMutation
To update the value status.Module
It is used to divide and manage modules. When the data is large, it is not easy to manage in the same file. In this case, modules can be encapsulated according to functional requirements.Plugins
It is a plug-in that can snapshot, record and trace the state of the data. It can realize the convenient management of the data state.- Auxiliary function
mapState
,mapGetters
,mapActions
,mapMutations
Etc is convenient for developers in the componentvm
In the processingstore
Data, easy to manage operations. When a component needs to obtain multiple states, declaring them as computed properties can be repetitive and redundant. To solve this problem, we can use the mapState helper function to help us generate computed properties.
Personal understanding:
3 How to Use Vuex?
The simplest Vuex example
Store. Js code:
import Vue from 'vue';
import Vuex form 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
// State is a repository of data, similar to data in a component
state: {
count: 0.
todos: [
{ id: 1.text: '... '.done: true },
{ id: 2.text: '... '.done: false }
]
},
// Define a "getter" (think of it as a calculated property of a store). Just like evaluating a property, the return value of a getter is cached according to its dependencies, and is only recalculated if its dependencies change.
getters: {
// Filter out all todo.done values that are true
doneTodos: state= > {
return state.todos.filter(todo= > todo.done)
}
},
Mutations is equivalent to methods in components, and is used to deal with synchronous events
mutations: {
// Autoincrement
increment(state) {
state.count++
},
// Decrement -- This takes two parameters. State represents the warehouse data and payload represents the payload to be operated on
decrease(state,payload){
state.count -= payload.decNum// Payload. decNum specifies the data to be decrement each time
}
},
// Handle asynchronous events
actions: {
increment(context){
context.commit("add");
},
/ *
Increment ({commit}){//
commit("add");
}
* /
incrementAsync({commit}){
setTimeout((a)= >{
commit("add");
},1000)
}
}
})
Copy the code
Test. Js code:
<template>
<div>
<h1>Data: {{$store. State. The count}}</h1>
<h1>Use computed properties: {{count}}</h1>
<button @click="addCount()">Data + 1</button>
</div>
</template>
<script>
export default {
computed: {
count(){
// The store has been globally mounted
return this.$store.state.count;
},
// Called through the store.getters object
doneTodos () {
return this.$store.getters.doneTodos
}
},
methods: {
addCount(){
}}}}}}}}}}}}}}}}}}}}}}
this.$store.commit("increment");
},
// Perform asynchronous operations
addAsync(){
this.$store.dispatch("incrementAsync");
},
}
}
</script>
Copy the code
In addition to using $store.state.count in the label, you can also use computed to obtain the state of the count data in the repository, but of course it is the same. We have seen whether it is complicated to obtain the corresponding data in the Store through computed each time. However, Vuex provides the corresponding data mapping mapState to import data in batches to the corresponding components, greatly simplifying our operation. Similarly, we can use the helper function mapGetters for mapping calculation, mapMutations, which maps the methods in the component to store.mit, mapActions, which maps the asynchronous functions in the component to Store.dispatch, To simplify the code.
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex';
export default {
/ *
computed: {{
count: state => state.count,
CountAlias: 'count', // the alias 'count' is equivalent to state => state.count
})}
* /
// A simplified version
computed: {
. mapState(["count"]),// Map this.count to store.state.count
. mapGetters(["doneTodosCount"]),// Use object expansion to mix getters into computed
. mapMutations([
increament,// Note that this must be a synchronization function
])
},
methods: {
. mapActions(["incrementAsync"])
}
}
Copy the code
In the above codestore
inVue
Is mounted globally so that it can be used globally in the projectVuex
Can inject the data stream into allVue
Component.The main. Js code:
import Vue from "vue";
import App from "./App.vue";
import store from "./store";
Vue.config.productionTip = false;
new Vue({
router,
store,
render: (h) = > h(App),
}).$mount("#app");
Copy the code
conclusion
I would like to use the most understandable language to express my understanding of Vuex, if there is any deviation in the understanding, please point out, thank you.
Reference documentation
- https://juejin.cn/post/6844903558496665607
- https://juejin.cn/post/6844903784708046855
- https://vuex.vuejs.org/zh/guide/actions.html