【vue源码解析】vue源码中一些不为人知的工具函数

[TOC]

记录和解读vue源码中一些常用的工具函数,在平常工作中或许可以用到这些巧妙的方法

isDef 判断变量是否已定义

1
2
3
export function isDef (v: any): boolean %checks {
return v !== undefined && v !== null
}

isPrimitive 判断变量是否是基本类型

1
2
3
4
5
6
7
8
9
10
11
12
/**
* Check if value is primitive.
*/
export function isPrimitive (value: any): boolean %checks {
return (
typeof value === 'string' ||
typeof value === 'number' ||
// $flow-disable-line
typeof value === 'symbol' ||
typeof value === 'boolean'
)
}

isPromise 判断是否是priomise

1
2
3
4
5
6
7
export function isPromise (val: any): boolean {
return (
isDef(val) &&
typeof val.then === 'function' &&
typeof val.catch === 'function'
)
}

isObject

1
2
3
4
5
6
7
8
/**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
*/
export function isObject (obj: mixed): boolean %checks {
return obj !== null && typeof obj === 'object'
}

hasOwn 判断对象自身是否有某个属性

1
2
3
4
5
6
7
/**
* Check whether an object has the property.
*/
const hasOwnProperty = Object.prototype.hasOwnProperty
export function hasOwn (obj: Object | Array<*>, key: string): boolean {
return hasOwnProperty.call(obj, key)
}

cached ?

1
2
3
4
5
6
7
8
9
10
/**
* Create a cached version of a pure function.
*/
export function cached<F: Function> (fn: F): F {
const cache = Object.create(null)
return (function cachedFn (str: string) {
const hit = cache[str]
return hit || (cache[str] = fn(str))
}: any)
}

camelize 横线风格转驼峰风格

1
2
3
4
5
6
7
8
/**
* Camelize a hyphen-delimited string.
* 把test-case形式转成testCase驼峰形式
*/
const camelizeRE = /-(\w)/g
export const camelize = cached((str: string): string => {
return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
})

热评文章