跳转到主内容
极星编程网:以代码为星,赴技术山海!

聊聊Vue3 shared模块下38个工具函数(源码阅读)

Vue3
的工具函数对比于
Vue2
的工具函数变化还是很大的,个人感觉主要还是体现在语法上,已经全面拥抱
es6
了;【相关推荐: vuejs视频教程 、 web前端开发 】 对比于工具类的功能变化并没有多少,大多数基本上都是一样的,只是语法上和实现上有略微的区别; 源码地址: vue-next vue-next/packages/shared/src/index.ts 之前介绍了很多阅读方式,这次就直接跳过了,直接开始阅读源码; 立即学习 “ 前端免费学习笔记(深入) ”; 所有工具函数
makeMap
: 生成一个类似于
Set
的对象,用于判断是否存在某个值
EMPTY_OBJ
: 空对象
EMPTY_ARR
: 空数组
NOOP
: 空函数
NO
: 返回
false
的函数
isOn
: 判断是否是
on
开头的事件
isModelListener
: 判断
onUpdate
开头的字符串
extend
: 合并对象
remove
: 移除数组中的某个值
hasOwn
: 判断对象是否有某个属性
isArray
: 判断是否是数组
isMap
: 判断是否是
Map
isSet
: 判断是否是
Set
isDate
: 判断是否是
Date
isRegExp
: 判断是否是
RegExp
isFunction
: 判断是否是函数
isString
: 判断是否是字符串
isSymbol
: 判断是否是
Symbol
isObject
: 判断是否是对象
isPromise
: 判断是否是
Promise
objectToString
:
Object.prototype.toString
toTypeString
:
Object.prototype.toString
的简写
toRawType
: 获取对象的类型
isPlainObject
: 判断是否是普通对象
isIntegerKey
: 判断是否是整数
key
isReservedProp
: 判断是否是保留属性
isBuiltInDirective
: 判断是否是内置指令
camelize
: 将字符串转换为驼峰
hyphenate
: 将字符串转换为连字符
capitalize
: 将字符串首字母大写
toHandlerKey
: 将字符串转换为事件处理的
key
hasChanged
: 判断两个值是否相等
invokeArrayFns
: 调用数组中的函数
def
: 定义对象的属性
looseToNumber
: 将字符串转换为数字
toNumber
: 将字符串转换为数字
getGlobalThis
: 获取全局对象
genPropsAccessExp
: 生成
props
的访问表达式 这其中有大部分和
Vue2
的工具函数是一样的,还有数据类型的判断,使用的是同一种方式,因为有了之前
Vue2
的阅读经验,所以这次快速阅读; 如果想要详细的可以看我之前写的文章: 【源码共读】Vue2源码 shared 模块中的36个实用工具函数分析 ; 而且这次是直接源码,
ts
版本的,不再处理成
js
,所以直接阅读
ts
源码; 正式开始 makeMap
export function makeMap( str: string, expectsLowerCase?: boolean ): (key: string) => boolean { const map: Record = Object.create(null) const list: Array = str.split(',') for (let i = 0; i < list.length; i++) { map[list[i]] = true } return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val] }
makeMap
的源码在同级目录下的
makeMap.ts
文件中,引入进来之后直接使用
export
关键字导出,实现方式和
Vue2
的实现方式相同; EMPTY_OBJ & EMPTY_ARR
export const EMPTY_OBJ: { readonly [key: string]: any } = __DEV__ ? Object.freeze({}) : {} export const EMPTY_ARR = __DEV__ ? Object.freeze([]) : []
EMPTY_OBJ
和
EMPTY_ARR
的实现方式和
Vue2
的
emptyObject
相同,都是使用
Object.freeze
冻结对象,防止对象被修改; NOOP
export const NOOP = () => {}
和
Vue2
的
noop
实现方式相同,都是一个空函数,移除了入参; NO
/** * Always return false. */ export const NO = () => false
和
Vue2
的
no
实现方式相同,都是一个返回
false
的函数,移除了入参; isOn
const onRE = /^on[^a-z]/ export const isOn = (key: string) => onRE.test(key)
判断是否是
on
开头的事件,并且
on
后面的第一个字符不是小写字母; isModelListener
export const isModelListener = (key: string) => key.startsWith('onUpdate:')
判断是否是
onUpdate:
开头的字符串; 参考: startWith extend
export const extend = Object.assign
直接拥抱
es6
的
Object.assign
,
Vue2
的实现方式是使用
for in
循环; remove
export const remove = (arr: T[], el: T) => { const i = arr.indexOf(el) if (i > -1) { arr.splice(i, 1) } }
对比于
Vue2
删除了一些代码,之前的快速删除最后一个元素的判断不见了; 猜测可能是因为有
bug
,因为大家都知道
Vue2
的数组响应式必须使用
Array
的
api
,那样操作可能会导致数组响应式失效; hasOwn
const hasOwnProperty = Object.prototype.hasOwnProperty export const hasOwn = ( val: object, key: string | symbol ): key is keyof typeof val => hasOwnProperty.call(val, key)
使用的是
Object.prototype.hasOwnProperty
,和
Vue2
相同; isArray
export const isArray = Array.isArray
使用的是
Array.isArray
,和
Vue2
相同; isMap & isSet & isDate & isRegExp
export const isMap = (val: unknown): val is Map => toTypeString(val) === '[object Map]' export const isSet = (val: unknown): val is Set => toTypeString(val) === '[object Set]' export const isDate = (val: unknown): val is Date => toTypeString(val) === '[object Date]' export const isRegExp = (val: unknown): val is RegExp => toTypeString(val) === '[object RegExp]'
都是使用
Object.toString
来判断类型,对比于
Vue2
新增了
isMap
和
isSet
和
isDate
,实现方式没变; isFunction & isString & isSymbol & isObject
export const isFunction = (val: unknown): val is Function => typeof val === 'function' export const isString = (val: unknown): val is string => typeof val === 'string' export const isSymbol = (val: unknown): val is symbol => typeof val === 'symbol' export const isObject = (val: unknown): val is Record => val !== null && typeof val === 'object'
和
Vue2
的实现方式相同,都是使用
typeof
来判断类型,新增了
isSymbol
; isPromise
export const isPromise = (val: unknown): val is Promise => { return isObject(val) && isFunction(val.then) && isFunction(val.catch) }
和
Vue2
对比修改了实现方式,但是判断逻辑没变; objectToString
export const objectToString = Object.prototype.toString
直接是
Object.prototype.toString
; Vue-router参考手册 Vue-router参考手册下载 下载 toTypeString
export const toTypeString = (value: unknown): string => objectToString.call(value)
对入参执行
Object.prototype.toString
; toRawType
export const toRawType = (value: unknown): string => { // extract "RawType" from strings like "[object RawType]" return toTypeString(value).slice(8, -1) }
和
Vue2
的实现方式相同; isPlainObject
export const isPlainObject = (val: unknown): val is object => toTypeString(val) === '[object Object]'
和
Vue2
的实现方式相同; isIntegerKey
export const isIntegerKey = (key: unknown) => isString(key) && key !== 'NaN' && key[0] !== '-' && '' + parseInt(key, 10) === key
判断一个字符串是不是由一个整数组成的; isReservedProp
export const isReservedProp = /*#__PURE__*/ makeMap( // the leading comma is intentional so empty string "" is also included ',key,ref,ref_for,ref_key,' + 'onVnodeBeforeMount,onVnodeMounted,' + 'onVnodeBeforeUpdate,onVnodeUpdated,' + 'onVnodeBeforeUnmount,onVnodeUnmounted' )
使用
makeMap
生成一个对象,用于判断入参是否是内部保留的属性; isBuiltInDirective
export const isBuiltInDirective = /*#__PURE__*/ makeMap( 'bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo' )
使用
makeMap
生成一个对象,用于判断入参是否是内置的指令; cacheStringFunction
const cacheStringFunction = string>(fn: T): T => { const cache: Record = Object.create(null) return ((str: string) => { const hit = cache[str] return hit || (cache[str] = fn(str)) }) as T }
同
Vue2
的
cached
相同,用于缓存字符串; camelize
const camelizeRE = /-(\w)/g /** * @private */ export const camelize = cacheStringFunction((str: string): string => { return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : '')) })
将
-
连接的字符串转换为驼峰式,同
Vue2
的
camelize
相同; capitalize
const hyphenateRE = /\B([A-Z])/g /** * @private */ export const hyphenate = cacheStringFunction((str: string) => str.replace(hyphenateRE, '-$1').toLowerCase() )
将驼峰式字符串转换为
-
连接的字符串,同
Vue2
的
hyphenate
相同; capitalize
/** * @private */ export const capitalize = cacheStringFunction( (str: string) => str.charAt(0).toUpperCase() + str.slice(1) )
将字符串首字母大写,同
Vue2
的
capitalize
相同; toHandlerKey
/** * @private */ export const toHandlerKey = cacheStringFunction((str: string) => str ? `on${capitalize(str)}` : `` )
将字符串首字母大写并在前面加上
on
; hasChanged
// compare whether a value has changed, accounting for NaN. export const hasChanged = (value: any, oldValue: any): boolean => !Object.is(value, oldValue)
和
Vue2
相比,移除了
polyfill
,直接使用
Object.is
; invokeArrayFns
export const invokeArrayFns = (fns: Function[], arg?: any) => { for (let i = 0; i < fns.length; i++) { fns[i](arg) } }
批量调用传递过来的函数列表,如果有参数,会将参数传递给每个函数; def
export const def = (obj: object, key: string | symbol, value: any) => { Object.defineProperty(obj, key, { configurable: true, enumerable: false, value }) }
使用
Object.defineProperty
定义一个属性,并使这个属性不可枚举; looseToNumber
/** * "123-foo" will be parsed to 123 * This is used for the .number modifier in v-model */ export const looseToNumber = (val: any): any => { const n = parseFloat(val) return isNaN(n) ? val : n }
将字符串转换为数字,如果转换失败,返回原字符串; 通过注释知道主要用于
v-model
的
.number
修饰符; toNumber
/** * Only conerces number-like strings * "123-foo" will be returned as-is */ export const toNumber = (val: any): any => { const n = isString(val) ? Number(val) : NaN return isNaN(n) ? val : n }
将字符串转换为数字,如果转换失败,返回原数据; getGlobalThis
let _globalThis: any export const getGlobalThis = (): any => { return ( _globalThis || (_globalThis = typeof globalThis !== 'undefined' ? globalThis : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : {}) ) }
获取全局对象,根据环境不同返回的对象也不同; genPropsAccessExp
const identRE = /^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/ export function genPropsAccessExp(name: string) { return identRE.test(name) ? `__props.${name}` : `__props[${JSON.stringify(name)}]` }
生成
props
的访问表达式,如果
name
是合法的标识符,直接返回
__props.name
,否则返回通过
JSON.stringify
转换后的
__props[name]
; 总结 通过这次的源码阅读,我们巩固了一些基础知识,通过对比
Vue2
的工具函数,我们也了解了
Vue3
的一些变化; 这些变化个人感觉主要集中在拥抱
es6
,可以看到放弃
ie
是多么自由而奔放; 话外题,不知道大家有没有发现
MDN
上面的浏览器兼容性表格,已经没有了
ie
的相关信息。 (学习视频分享: vuejs入门教程 、 编程基础视频 )

相关文章