This chapter has been read more than 3 million times on CSDN and is the most popular chapter in this series. From a certain point of view, the explanation of mapstate in this article is even better than that in the official website (I learned this from others’ comments). At present, the search weight of this article on baidu has surpassed that of the official website. In fact, I did not feel that this article is much out of color, compared with the real big guy, the gap is not a bit, no more gossip to say, the following began to serious blog move.
1.state
What is state?
Definition: State (VUex) ≈ data (VUE).
Vuex’s state has many similarities with VUE’s data in that it is used to store some data, or state values. These values will be mounted to the data and DOM’s bidirectional binding events, which trigger DOM updates when you change the value.
Although state and data have many similarities, state is generally mounted on computed attributes of child components when it is used, which makes it easier to respond to child components when the value of state changes. If you use data to receive $store.state, you can receive the value, but since this is a simple assignment, the state change cannot be detected by data in vue. You can also use watch $store to fix this problem. (I reviewed the logic of this paragraph, the logic itself is fine, but for beginners may not be very friendly, can skip)
To sum up, use computed to receive state as follows:
//state.js let state = {count: 1, name: 'DKR ', sex:' male ', from: 'China'} export default stateCopy the code
<template>
<div id="example">
<button @click="decrement">-</button>
{{count}}
{{dataCount}}
<button @click="increment">+</button>
</div>
</template>
<script>
export default {
data () {
return {
dataCount: this.$store.state.count // Receive with data}},computed: {count(){
return this.$store.state.count // Use computed reception}}methods: {
increment () {
this.$store.commit('increment')
},
decrement () {
this.$store.commit('decrement')}}}</script>
Copy the code
The result is that values received with data do not respond to updates in a timely manner, as can be done with computed data.
2. MapState auxiliary function
What is mapState?
MapState is an auxiliary function of state. That may be hard to understand
MapState is the grammar sugar of the state. You may want to scold me for saying that you have no idea what grammar sugar is. In fact, I have my own definition of grammar sugar. My understanding of grammar sugar is that before using it, I feel that I am already very skilled in a kind of operation, and there is no problem with this operation, why use the so-called “better operation”. After using it for a period of time, it really smells good!
What it actually does: 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 that will save you from pressing the key.
Before using mapState, import this helper function.
import { mapState } from 'vuex'
Copy the code
Then there’s how to use it:
<template>
<div id="example">
<button @click="decrement">-</button>
{{count}}
{{dataCount}}
<button @click="increment">+</button>
<div>{{sex}}</div>
<div>{{from}}</div>
<div>{{myCmpted}}</div>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
data () {
return {
str: 'citizenship'.dataCount: this.$store.state.count
}
},
computed: mapState({
count: 'count'.// The first way
sex: (state) = > state.sex, // The second way
from: function (state) { // Use the normal function this to point to the vue instance, beware
return this.str + ':' + state.from
},
// Note that the arrow function's this pointer does not point to the vue instance, so do not abuse the arrow function
// from: (state) => this.str + ':' + state.from
myCmpted: function () {
// No state is needed here, so test the old usage of computed
return 'test' + this.str
}
}),
methods: {
increment () {
this.$store.commit('increment')
},
decrement () {
this.$store.commit('decrement')
}
},
created () {
// Write a timer and find that computed still maintains that changes in internal properties, whether in the current instance data or in values in vuEX, trigger DOM and value updates
setTimeout(() = > {
this.str = 'countries'
}, 1000)}}</script>
Copy the code
For use with computed to receive the value returned by the mapState function, you can receive the value in store in one of three ways, see the comments.
In fact, the second and the third is the same, just the former with the lazy ES6 syntax, arrow function, must pay attention to a problem when I being lazy, this pointer pointing to the problem, I have already mentioned in many articles do not use the arrow to be lazy in the vue function, can cause a lot of hard to detect errors, if you are using at the same time also need to state To use this for the current vue instance, be sure to write it normally.
Of course, computed does not lose its functionality by introducing the mapState helper function – it is used to extend the data of the current VUE, but it is a bit odd to write it, if you have already written a lot of computed properties and are halfway through it when you want to introduce vuex and still want to use the mapState helper function You may need to do the following things.
// Previously computed computed:{fn1(){return... }, fn2(){ return ... }, fn3(){ return ... }... } // Computed :mapState({// Copy and paste fn1(){return... }, fn2(){ return ... }, fn3(){ return ... }... Vuex count:'count'....... })Copy the code
As you can see from the above, this doesn’t match some of the unexplained features of the code. We wish we could use mapState instead of doing useless copy-and-paste operations, and hope it will automatically integrate into the current production environment. Ok,ES6+(or ES7) provides this convenience.
3. …mapState
In fact… MapState is not an extension of mapState, but… Extension of the object expander. And of course if you use it here you’ll see that it makes the code look a little bit more conventionally logical, and you’ll see why.
First, a review… The representation of an object expander in an array is explained in ES6 syntax learning categories:
Let arr = [1,2,3] console.log(... Arr) / / 1, 2, 3Copy the code
Here’s an example:
Let MapState = MapState ({count: 'count', sex: (state) => state.sex}) let json = {'a': 'I am json ',... MapState } console.log(json)Copy the code
Json can successfully merge the JSON format of mapState return and the A attribute of JSON into a new object. You can call this object mixing. So, you’re free to use mapState.
// Previously computed computed:{fn1(){return... }, fn2(){ return ... }, fn3(){ return ... }... } // Computed :{// Keep the original fn1(){return... }, fn2(){ return ... }, fn3(){ return ... }... // Maintain vuex... MapState ({// here... Count :'count'})}Copy the code
This is the end of this chapter, the next chapter is about getters,mapGetters… In mapGetters, give a thumbs up to those interested in this series
Never forget why you started, and your mission can be accomplished.
You can also scan the QR code to enter the blogger’s fan group (708637831). Of course, you can also scan the QR code to reward and directly keep a handsome blogger.