[Source Code]Vue3 — Utility Function In 5 Minutes

Table Of Content

Why Vue3 Utility Function Worth Reading

How To Read Source Code

Download and Run vue-next(vue3)

git clone https://github.com/vuejs/vue-next.git
cd vue-next
preinstall setting
https://github.com/vuejs/vue-next/blob/ccb6651b12af6d1b43e2391cef77fd0bb73e49bd/scripts/preinstall.js
pnpm install
nr dev:sourcemap

Study Vue3 Utility Function

CONST:

determine type
Array.isArray([]) //true
Array.isArray(new Array()) //true
Array.isArray(Array.prototype) //true
export const isMap = (val: unknown): val is Map<any, any> =>
toTypeString(val) === '[object Map]'
export const isSet = (val: unknown): val is Set<any> =>
toTypeString(val) === '[object Set]'
export const objectToString = Object.prototype.toString
export const toTypeString = (value: unknown): string =>
objectToString.call(value)
export const isDate = (val: unknown): val is Date => val instanceof Date
var child = new Father();
child instanceof Father; // true,because Object.getPrototypeOf(child) === Father.prototype

isFunction, isString, isSymbol and isObject(use typeof)

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<any, any> =>
val !== null && typeof val === 'object'
export const isPromise = <T = any>(val: unknown): val is Promise<T> => {
return isObject(val) && isFunction(val.then) && isFunction(val.catch)
}

Convert Type

export const objectToString = Object.prototype.toStringexport const toTypeString = (value: unknown): string =>
objectToString.call(value)
export const toRawType = (value: unknown): string => {
// extract "RawType" from strings like "[object RawType]"
return toTypeString(value).slice(8, -1)
}
export const toNumber = (val: any): any => {
const n = parseFloat(val)
return isNaN(n) ? val : n
}
Photo by Iyan Kurnia on Unsplash
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
: {})
)
}

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store