- This is the 24th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
Vuex_State
Vuex is a state management tool for VUE, to facilitate the realization of multiple components to share state.
The installation
npm install vuex --save
Copy the code
use
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
count: 0}})new Vue({
store,
})
Copy the code
State
A single state tree, with a single object, contains all the application-level states.
Get the Vuex state in the Vue component
Vuex provides a mechanism to “inject” state from the following component into each child component through the Store option (call vue.use (Vuex)).
By registering the Store option in the root instance, the store instance is injected into all the children of the root component, which can be accessed through this.$store.
<div class="home">
{{ $store.state.count }}
</div>
Copy the code
MapState helper function
When a component needs to fetch multiple states, it can be repetitive and redundant to declare all those states as computed properties. To solve this problem, we can use the mapState helper function to help us generate calculated properties:
import { mapState } from 'vuex'; computed: { ... mapState(['count']),},Copy the code
Use different names:
computed: { ... mapState({storeCount: state= > state.count,
/ / short
storeCount: 'count'.// Equivalent to state => state.count})},Copy the code
Vuex_Getter
The computed properties of store. The return value of a getter is cached based on its dependency and is recalculated only if its dependency value changes.
The Getter receives state as its first argument and getters as its second argument.
getters: {
doubleCount (state) {
return state.count * 2; }}Copy the code
Access by property
Getter will be exposed to the store. Getters object: this. $store. Getters. DoubleCount
Access by method
You can also pass parameters to the getter by having the getter return a function
getters: {
addCount: state= > num= > state.count + num;
}
Copy the code
this.$store.addCount(3);
Copy the code
MapGetters helper function
import { mapsGetters } from 'vuex';
export default {
computed: {
...mapGetters([
'doubleCount'.'addCount',])}}Copy the code
If you want to give a getter property another name, use object form:
mapGetters({
/ / the ` enclosing doneCount ` mapping for ` enclosing $store. Getters. DoneTodosCount `
storeDoubleCount: 'doubleCount'
})
Copy the code
The last
If it is helpful to you, I hope to give you a 👍 comment/collection/three even!
Bloggers are honest and answer questions for free ❤