VueX源码分析(2)

剩余内容

  • /module
  • /plugins
  • helpers.js
  • store.js

helpers要从底部开始分析比较好。也即先从辅助函数开始再分析那4个map函数mapState

helpers.js

getModuleByNamespace

/**
* Search a special module from store by namespace. if module not exist, print error message.
* @param {Object} store
* @param {String} helper
* @param {String} namespace
* @return {Object}
*/
function getModuleByNamespace (store, helper, namespace) {
const module = store._modulesNamespaceMap[namespace]
if (process.env.NODE_ENV !== 'production' && !module) {
console.error(`[vuex] module namespace not found in ${helper}(): ${namespace}`)
}
return module
}

解析:

  • 通过namespace来寻找module,如果找不到打印错误信息(开发环境)
  • _modulesNamespaceMap这个Map存有所有的module
  • 在vuex中,不同的作用域用'/'来分隔开的(嵌套模块),如商城中的购物车的namespace可以这样表示'shop/shopping_cart'

normalizeMap

/**
* 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) {
return Array.isArray(map)
? map.map(key => ({ key, val: key }))
: Object.keys(map).map(key => ({ key, val: map[key] }))
}

解析:

  • 将数组或者对象转化成[Map, Map]的格式,Map关键字有{ key, val }
  • 如果是数组,生成Map的key === val
  • 如果是对象,生成Map的key就是对象的键名,val就是对象的值

normalizeNamespace

/**
* Return a function expect two param contains namespace and map. it will normalize the namespace and then the param's function will handle the new namespace and the map.
* @param {Function} fn
* @return {Function}
*/
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)
}
}

解析:

  • 这里的fn就是mapState等4大map函数,使用柯里化缓存fn
  • typeof namespace !== 'string'第一个判断是支持两种传参模式:1、可以不传namespace直接传map,如mapActions(['action']);2、支持传namespace,如mapActions('shop', ['action'])
  • 也即namespace可传可不传,不传最后初始化namespace = ''
  • 如果传了namespace,要检查最后一个字符带不带'/',没有则补全
  • 这个函数就是在执行mapState、mapAction等4大map函数之前的namespace预处理,最终才把namesapce和map传个fn函数

createNamespacedHelpers

/**
* Rebinding namespace param for mapXXX function in special scoped, and return them by simple object
* @param {String} namespace
* @return {Object}
*/
export const createNamespacedHelpers = (namespace) => ({
mapState: mapState.bind(null, namespace),
mapGetters: mapGetters.bind(null, namespace),
mapMutations: mapMutations.bind(null, namespace),
mapActions: mapActions.bind(null, namespace)
})

解析:

  • 这个bind函数涉及到柯里化,要理解柯里化才可理解这个意思
  • 柯里化和函数的参数个数有关,可以简单把柯里化理解成是一个收集参数的过程,只有收集够函数所需的参数个数,才会执行函数体,否则返回一个缓存了之前收集的参数的函数。
  • 4大map函数都要接受两个参数,namespace和map
  • 由柯里化:mapState函数有2个参数,要收集够2个参数才会执行mapState的函数体
  • createNamespacedHelpers的作用是让mapState收集第一个参数namespace,由于还差一个参数map,所以返回的是一个缓存了namespace参数的函数,继续接收下一个参数map
  • 所以被createNamespacedHelpers返回的mapState只需传入1个参数map就可以执行了,且传入的第一个参数必须是map,因为namespace已经收集到了,再传入namespace最终执行的结果会是mapState(namespace, namespace)
  • 总之,如果了解过柯里化,这里应该很好理解。

mapState、mapMutations、mapActions、mapGetters

mapState

/**
* Reduce the code which written in Vue.js for getting the state.
* @param {String} [namespace] - Module's namespace
* @param {Object|Array} states # Object's item can be a function which accept state and getters for param, you can do something for state and getters in it.
* @param {Object}
*/
export const mapState = normalizeNamespace((namespace, states) => {
const res = {}
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
})

解析:

  • 4大map函数最终结果都是返回一个对象{}
  • mappedState其实就是computed的属性的函数,看这个函数要联想到computed,且这个函数的this也是指向vue的
  • 上面的this.$state.statethis.$state.getters是全局的stategetters
  • 接下来就是判断是不是模块,是则拿到模块的state和getter。有种情况用到mapState({ name: (state, getter) => state.name })
  • 最后返回 val 。如果是函数,如上面那样要先执行一遍,再返回函数执行后的值
  • 因为mappedState就是computed中属性的函数,一定是要返回值的。
  • res是个对象,所以可以{ computed: { ...mapState(['name', 'age']) } }
// mapState(['name', 'age'])
const res = {
// { key, val } 其中: key = 'name' val = 'name' name: function mappedState () {
// 没有命名空间的情况
// 这个函数要用到computed的,这里this指向Vue组件实例
return this.$store.state[name]
},
age: function mappedState () {
// 如果有命名空间的情况
// 如上面源码根据namespace拿到模块module
const state = module.context.state
return state[age]
}
} // mapState({ name: (state, getter) => state.name })
const res = {
// { key, val } 其中:key = 'name' val = (state, getter) => state.name name: function mappedState () {
// 没有命名空间
// 如上面代码一样{ key, val }中的 val = (state, getter) => state.name }
const state = this.$store.state
cosnt getter = this.$store.getter
// this 是指向Vue组件实例的
return val.call(this, state, getter)
}
}

mapMutations

/**
* Reduce the code which written in Vue.js for committing the mutation
* @param {String} [namespace] - Module's namespace
* @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept anthor params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function.
* @return {Object}
*/
export const mapMutations = normalizeNamespace((namespace, mutations) => {
const res = {}
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
})

解析:

  • 这里也要判断是不是模块,不同情况的commit不同,是用全局的还是用模块的
  • mappedMutationmethods的函数,this同样指向Vue的实例
  • val.apply(this, [commit].concat(args)),是这种情况mapMutations({ mutationName: (commit, ...arg) => commit('自定义') })
  • commit.apply(this.$store, [val].concat(args)),是这种情况mapMutations(['CHANGE_NAME'])使用的时候还可以传参数this['CHANGE_NAME'](name)

mapGetters

/**
* Reduce the code which written in Vue.js for getting the getters
* @param {String} [namespace] - Module's namespace
* @param {Object|Array} getters
* @return {Object}
*/
export const mapGetters = normalizeNamespace((namespace, getters) => {
const res = {}
normalizeMap(getters).forEach(({ key, val }) => {
// thie namespace has been mutate by normalizeNamespace
val = namespace + val
res[key] = function mappedGetter () {
if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) {
return
}
if (process.env.NODE_ENV !== 'production' && !(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
})

解析:

  • val = namespace + val这里是,不管是模块的getter还是全局的getter最终都存在一个地方中($store.getters),是模块的会有'/,所以这里要补充namespace + val
  • 所以最后返回的是this.$store.getters[val]
  • 还有mappedGetter对应computed属性的函数,this指向Vue实例

mapActions

/**
* Reduce the code which written in Vue.js for dispatch the action
* @param {String} [namespace] - Module's namespace
* @param {Object|Array} actions # Object's item can be a function which accept `dispatch` function as the first param, it can accept anthor params. You can dispatch action and do any other things in this function. specially, You need to pass anthor params from the mapped function.
* @return {Object}
*/
export const mapActions = normalizeNamespace((namespace, actions) => {
const res = {}
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
})

解析:

  • 这个和mapMutations差不多,只是commit换成了dispatch
  • mappedAction对应methods的属性的函数,this也是指向Vue实例

VueX源码分析(2)的更多相关文章

  1. VueX源码分析(5)

    VueX源码分析(5) 最终也是最重要的store.js,该文件主要涉及的内容如下: Store类 genericSubscribe函数 resetStore函数 resetStoreVM函数 ins ...

  2. VueX源码分析(3)

    VueX源码分析(3) 还剩余 /module /plugins store.js /plugins/devtool.js const devtoolHook = typeof window !== ...

  3. VueX源码分析(4)

    VueX源码分析(4) /module store.js /module/module.js import { forEachValue } from '../util' // Base data s ...

  4. VueX源码分析(1)

    VueX源码分析(1) 文件架构如下 /module /plugins helpers.js index.esm.js index.js store.js util.js util.js 先从最简单的 ...

  5. 逐行粒度的vuex源码分析

    vuex源码分析 了解vuex 什么是vuex vuex是一个为vue进行统一状态管理的状态管理器,主要分为state, getters, mutations, actions几个部分,vue组件基于 ...

  6. vuex源码分析3.0.1(原创)

    前言 chapter1 store构造函数 1.constructor 2.get state和set state 3.commit 4.dispatch 5.subscribe和subscribeA ...

  7. vuex 源码分析(七) module和namespaced 详解

    当项目非常大时,如果所有的状态都集中放到一个对象中,store 对象就有可能变得相当臃肿. 为了解决这个问题,Vuex允许我们将 store 分割成模块(module).每个模块拥有自己的 state ...

  8. vuex 源码分析(六) 辅助函数 详解

    对于state.getter.mutation.action来说,如果每次使用的时候都用this.$store.state.this.$store.getter等引用,会比较麻烦,代码也重复和冗余,我 ...

  9. vuex 源码分析(五) action 详解

    action类似于mutation,不同的是Action提交的是mutation,而不是直接变更状态,而且action里可以包含任意异步操作,每个mutation的参数1是一个对象,可以包含如下六个属 ...

随机推荐

  1. JAVA接口详细讲解

    接口 接口的概念  接口代表的是一个功能的集合,定义规范,所有的方法都是抽像方法,这是一种思想是一种规则,将这个种规则称为接口. 接口的定义 使用关键字 interface 叫做接口 修饰符 inte ...

  2. pyinstaller打包多个py文件仍报错ModuleNotFoundError: No module named 'xxx'

    [问题现象] 使用pyinstaller A.py -p b.py -p c.py打包多个文件 或者使用main.spec在Analysis配置好各个文件打包 打包成功后,运行main.exe仍然报错 ...

  3. [WebShow系列] 倒计时展示相关问题

    WebShow内置了倒计时功能. 后台参数维护: 倒计时参数说明: 倒计时基准时间设置(秒数):假设设置为90,也就是从1分30秒开始倒计时,同时有开始提示音. 倒计时提示1剩余秒数:假设设置为30, ...

  4. iOS 技术支持

    iOS 技术支持网址:有问题或建议请留言. 邮箱地址:odeyrossskudder4266848@mail.com iOS program design & system consultat ...

  5. Leetcode:单调数列

    题目 如果数组是单调递增或单调递减的,那么它是单调的. 如果对于所有 i <= j,A[i] <= A[j],那么数组 A 是单调递增的. 如果对于所有 i <= j,A[i]> ...

  6. bzoj3295: [Cqoi2011]动态逆序对 三维数点

    为了便于考虑,把删除反序变为增加 于是就变成关于权值和位置和时间的三维数点 一波cdq一波树状数组教做人 (神TM需要longlong,80了一发) #include <bits/stdc++. ...

  7. Python 开发基础-字符串类型讲解(字符串方法)-2

    s = 'Hello World!'print(s.index('W',0,9))#返回某个字母的索引值,本例返回6.没有该字母会报错,和FIND比较像,find不会报错,没找到会返回-1print( ...

  8. Python 踩坑之旅进程篇其三pgid是个什么鬼 (子进程\子孙进程无法kill 退出的解法)

    目录 1.1 踩坑案例 1.2 填坑解法 1.3 坑位分析 1.4.1 技术关键字 下期坑位预告 代码示例支持 平台: Centos 6.3 Python: 2.7.14 Github: https: ...

  9. 使用Spring Security OAuth2进行简单的单点登录

    1.概述 在本教程中,我们将讨论如何使用Spring Security OAuth和Spring Boot实现SSO - 单点登录. 我们将使用三个单独的应用程序: 授权服务器 - 这是中央身份验证机 ...

  10. 关于死循环while(true){}或for(;;){}的总结

    关于死循环while(true){}或for(;;){}的总结 1.基本用法: while(true){     语句体; } for(;;){     语句体; } 以上情况,语句体会一直执行. 2 ...