Vuex accurately obtains a field of an object in the state through mapState

We all know that public data written in vuex
can be passed

import {
    
     mapState } from 'vuex'
export default {
    
    
     computed:{
    
    
	    ...mapState(['dom'])
	  }
}

This method is quickly defined in the computed properties of the current component
, but if we store an object and we only want one of its fields, then it is very troublesome to write this way

For example,
we define a user object in the state of vuex, which has two fields, token and userInfo,
then we can write like this

import {
    
     mapState } from 'vuex'
export default {
    
    
     computed:{
    
    
	    ...mapState(['user'])
	  }
}

In this way, we can get the object directly from this.user in the component.
So what if we only need the userInfo under user?
Some people may think that I get the user and then go to userInfo, isn't it all right?
Yes, but we have a better solution,
which is

import {
    
     mapState } from 'vuex'

export default {
    
    
  ...mapState({
    
    
    userInfo: state => state.user.userInfo
  }),
}

In this way, we define a calculated property userInfo whose value comes from userInfo under user under state
so that our code will also have better readability

Guess you like

Origin blog.csdn.net/weixin_45966674/article/details/132610181