Vuex's understanding of state

1. What is it state?

  • As mentioned in the previous article, it Vuexis to provide a warehouse, and there are many objects in the warehouse. Among them stateis the storage place of the data source , which corresponds to the inside of the general Vueobject (the and corresponding to the datalater mentioned ).actionsmutationsmethods

  • Responsive book storage : stateThe data stored in it is responsive, and Vuecomponents read data storefrom it . If storethe data in the book changes, the components that depend on this data will also be updated. (here " state " = " data "), that is, the data and the view are synchronized.


2. Local state

  • Get: VueGet data in the component, the most direct way can be obtained through the computed property;

  • Components can still save local state : Although Vuexthe Storewarehouse makes it more convenient for us to manage data at the same time, the code will also become verbose. The data of some components is strictly for their own use, we can put them statein the component itself as a local Data is used exclusively for this component, other components cannot.


3.mapState

  • mapStateThe role is to   map  the global state sum  to the  computed property of the current component, .getterscomputedthis.$store.state

  • Example of use

     import {mapState} from 'vuex' 
     export default {
      computer :
      mapState({
       count: state => state.count,
        'count' // 映射 this.count 为 store.state.count
      })
    }
  • look at the source code

    export function mapState (states) {
       const res = {}   //定义一个对象
       normalizeMap(states).forEach(({ key, val }) => {
        // normalizeMap()函数初始化states数据
             res[key] = function mappedState () {
               return typeof val === 'function'
               // 判断val是否是函数
               ? val.call(this, this.$store.state, this.$store.getters)
               // 若val是函数,将store的state和getters作为参数,返回值作为mapped State的返回值
               : this.$store.state[val]}})
           return res // 返回的是一个函数
        }
    //初始化方法
    -------------------------------------------------------------------------    
     function normalizeMap (map) {
            return Array.isArray(map) //判断state是否是数组
            ? map.map(key => ({ key, val: key }))
           // 是数组的话,调用map方法,将每一个数组元素转换成{key,val:key}
           : Object.keys(map).map(key => ({ key, val: map[key] }))
           // 否则就是对象,遍历对象,将每一个val变成val:key
       }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325941359&siteId=291194637