vuex工具函数(mapXXX)原理解读。

vuex工具函数原理解读

不论是vuex3还是vuex4在工具函数这一部分的主要原理是不变的,即可以不去特别分开理解。

在理解工具函数原理前先解读一下store对象上重要的属性:

js 复制代码
// store internal state
//属性是这些,但是getters和state的初始化不是在这进行
    this._committing = false
    this._actions = Object.create(null)
    this._actionSubscribers = []
    this._mutations = Object.create(null)
    this._wrappedGetters = Object.create(null)
    this._modules = new ModuleCollection(options)
    this._modulesNamespaceMap = Object.create(null)
    this._subscribers = []
    this._makeLocalGettersCache = Object.create(null)
	this.getters = {}
	this.state = {}

工具函数中主要访问到的属性是_modulesNamespaceMapstate以及getters

这些工具函数中都用到了三个函数,先来看这三个函数内容吧:

js 复制代码
function normalizeNamespace (fn) {
  return (namespace, map) => {
    if (typeof namespace !== 'string') {
      map = namespace
      namespace = ''
    } else if (namespace.charAt(namespace.length - 1) !== '/') {
      namespace += '/'
    }
    return fn(namespace, map)
  }
}

/**
 * Normalize the map
 * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ]
 * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ]
 * @param {Array|Object} map
 * @return {Object}
 */
function normalizeMap (map) {
  if (!isValidMap(map)) {
    return []
  }
  return Array.isArray(map)
    ? map.map(key => ({ key, val: key }))
    : Object.keys(map).map(key => ({ key, val: map[key] }))
}

function getModuleByNamespace (store, helper, namespace) {
  const module = store._modulesNamespaceMap[namespace]
  if (__DEV__ && !module) {
    console.error(`[vuex] module namespace not found in ${helper}(): ${namespace}`)
  }
  return module
}
  1. normalizeNamespace:包装接收到的函数,使namespace是空字符串或者moduleName/的格式,例如user/,使map是一个数组或者对象。

  2. normalizeMap:让map是一个装着特定对象的数组。

    ts 复制代码
    interface obj {
        key: any
        val: any
    }
    type map = obj[]
  3. getModuleByNamespace:获取_moduelsNamespaceMap属性下的模块。

mapState源码:

js 复制代码
export const mapState = normalizeNamespace((namespace, states) => {
  const res = {}
  if (__DEV__ && !isValidMap(states)) {
    console.error('[vuex] mapState: mapper parameter must be either an Array or an Object')
  }
  normalizeMap(states).forEach(({ key, val }) => {
    res[key] = function mappedState () {
      let state = this.$store.state
      let getters = this.$store.getters
      if (namespace) {
        const module = getModuleByNamespace(this.$store, 'mapState', namespace)
        if (!module) {
          return
        }
        state = module.context.state
        getters = module.context.getters
      }
      return typeof val === 'function'
        ? val.call(this, state, getters)
        : state[val]
    }
    // mark vuex getter for devtools
    res[key].vuex = true
  })
  return res
})

可以看出两种使用该方法的方式:

  1. 使用子模块的属性方法
js 复制代码
mapState('moduleName/',['state1','state2'])
  1. 使用$store的属性方法
js 复制代码
mapState(['state1','state2'])

而这个方法返回的一个所有属性都是一个函数的对象,每个属性函数都有一个返回值,这也就是为什么mapState是写在computed中作为计算属性的原因。

mapMutations:

js 复制代码
export const mapMutations = normalizeNamespace((namespace, mutations) => {
  const res = {}
  if (__DEV__ && !isValidMap(mutations)) {
    console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object')
  }
  normalizeMap(mutations).forEach(({ key, val }) => {
    res[key] = function mappedMutation (...args) {
      // Get the commit method from store
      let commit = this.$store.commit
      if (namespace) {
        const module = getModuleByNamespace(this.$store, 'mapMutations', namespace)
        if (!module) {
          return
        }
        commit = module.context.commit
      }
      return typeof val === 'function'
        ? val.apply(this, [commit].concat(args))
        : commit.apply(this.$store, [val].concat(args))
    }
  })
  return res
})

mapGetters:

js 复制代码
export const mapGetters = normalizeNamespace((namespace, getters) => {
  const res = {}
  if (__DEV__ && !isValidMap(getters)) {
    console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object')
  }
  normalizeMap(getters).forEach(({ key, val }) => {
    // The namespace has been mutated by normalizeNamespace
    val = namespace + val
    res[key] = function mappedGetter () {
      if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) {
        return
      }
      if (__DEV__ && !(val in this.$store.getters)) {
        console.error(`[vuex] unknown getter: ${val}`)
        return
      }
      return this.$store.getters[val]
    }
    // mark vuex getter for devtools
    res[key].vuex = true
  })
  return res
})

mapActions:

js 复制代码
export const mapActions = normalizeNamespace((namespace, actions) => {
  const res = {}
  if (__DEV__ && !isValidMap(actions)) {
    console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object')
  }
  normalizeMap(actions).forEach(({ key, val }) => {
    res[key] = function mappedAction (...args) {
      // get dispatch function from store
      let dispatch = this.$store.dispatch
      if (namespace) {
        const module = getModuleByNamespace(this.$store, 'mapActions', namespace)
        if (!module) {
          return
        }
        dispatch = module.context.dispatch
      }
      return typeof val === 'function'
        ? val.apply(this, [dispatch].concat(args))
        : dispatch.apply(this.$store, [val].concat(args))
    }
  })
  return res
})

总结

mapXXX工具函数都是通过normalizeNamespace接收一个fn函数返回一个包装函数wrapFn,而wrapFn返回的是一个全部属性都是函数的对象。

  • mapState:读取$store或者module.context.state上的属性,返回一个属性函数对象 ,每个属性都有一个返回值,这个返回值即指定state的值。
  • mapMutations:读取$store上的commit方法或者module.context上的commit方法。
  • mapGetters:读取$store上的getters属性。
  • mapActions:读取$store上的dispatch方法或者module.context上的dispatch方法。
相关推荐
ZC跨境爬虫1 天前
跟着 MDN 学 HTML day_37:(深入掌握 CustomEvent 自定义事件接口)
前端·javascript·ui·html·音视频
码海扬帆:前端探索之旅1 天前
深度定制 uni-combox:新增功能详解与实战指南
前端·vue.js·uni-app
谷雨不太卷1 天前
进程的状态码
java·前端·算法
打小就很皮...1 天前
基于 Python + LangChain + RAG 的知识检索系统实战
前端·langchain·embedding·rag
BJ-Giser1 天前
Cesium 烟雾粒子特效
前端·可视化·cesium
空中海1 天前
02 ArkTS 语言与工程规范
java·前端·spring
YJlio1 天前
7.4.5 Windows 11 企业网络连接与网络重置实战:远程访问、本地策略与故障恢复
前端·chrome·windows·python·edge·机器人·django
Slow菜鸟1 天前
Codex CLI 教程(五)| Skills 安装指南:面向 Java 全栈工程师打造个人 ECC(V1版)
大数据·前端·人工智能
Lee川1 天前
打字机是怎么炼成的:Chat 流式输出深度解析
前端·后端·面试
前端若水1 天前
过渡(transition)高级:贝塞尔曲线、硬件加速
前端·css·css3