Vuex: an instance for understanding the usage of state, and a vuexstate instance
1. What is state?
As mentioned in the previous article,Vuex
A repository contains many objects. Wherestate
Is the data source storage location, correspondingVue
Objectdata
(As mentioned lateractions
Andmutations
Correspondsmethods
).
Answer book storage:state
The stored data is responsive,Vue
Component slavestore
Read data, ifstore
The data in is changed, and the component dependent on the data is updated. (Here "status" = "data"), that is, data and views are synchronized.
2. Local Status
Obtain: InVue
Obtain data from components, which can be obtained directly through calculation attributes;
The component can still save the local status: althoughVuex
OfStore
A repository makes it easier for us to manage data in the same way, but more code will also become lengthy. Some components have their own data, so we canstate
It is placed on the component itself and used as local data for use by this component. Other components cannot be used.
3. mapState
mapState
The rolestate
Andgetters
Map to the current componentcomputed
Calculating attributes,this.$store.state
.
Example
Import {mapState} from 'vuex' export default {computer: mapState ({count: state => state. count, 'Count' // map this. count is store. state. count })}
Look at the source code
Export function mapState (states) {const res ={} // defines an object normalizeMap (states ). forEach ({key, val}) =>{// normalizeMap () function initializes states data res [key] = function mappedState () {return typeof val = 'function' // determines whether val is a function? Val. call (this, this. $ store. state, this. $ store. getters) // If val is a function, store state and getters are used as parameters, and the return value is the return value of mapped State: this. $ store. state [val]}) return res // returns a function} // initialization method function normalizeMap (map) {return Array. isArray (map) // determines whether the state is an array? Map. map (key => ({key, val: key}) // if it is an array, call the map method to convert each array element to {key, val: key }: object. keys (map ). map (key => ({key, val: map [key]}) // otherwise it is an object. traverse the object and convert every val to val: key}
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.