您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“Vue3 shared模塊下的工具函數(shù)有哪些”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“Vue3 shared模塊下的工具函數(shù)有哪些”吧!
Vue3
的工具函數(shù)對(duì)比于Vue2
的工具函數(shù)變化還是很大的,個(gè)人感覺主要還是體現(xiàn)在語法上,已經(jīng)全面擁抱es6
了;
對(duì)比于工具類的功能變化并沒有多少,大多數(shù)基本上都是一樣的,只是語法上和實(shí)現(xiàn)上有略微的區(qū)別。
makeMap
: 生成一個(gè)類似于Set
的對(duì)象,用于判斷是否存在某個(gè)值
EMPTY_OBJ
: 空對(duì)象
EMPTY_ARR
: 空數(shù)組
NOOP
: 空函數(shù)
NO
: 返回false
的函數(shù)
isOn
: 判斷是否是on
開頭的事件
isModelListener
: 判斷onUpdate
開頭的字符串
extend
: 合并對(duì)象
remove
: 移除數(shù)組中的某個(gè)值
hasOwn
: 判斷對(duì)象是否有某個(gè)屬性
isArray
: 判斷是否是數(shù)組
isMap
: 判斷是否是Map
isSet
: 判斷是否是Set
isDate
: 判斷是否是Date
isRegExp
: 判斷是否是RegExp
isFunction
: 判斷是否是函數(shù)
isString
: 判斷是否是字符串
isSymbol
: 判斷是否是Symbol
isObject
: 判斷是否是對(duì)象
isPromise
: 判斷是否是Promise
objectToString
: Object.prototype.toString
toTypeString
: Object.prototype.toString
的簡寫
toRawType
: 獲取對(duì)象的類型
isPlainObject
: 判斷是否是普通對(duì)象
isIntegerKey
: 判斷是否是整數(shù)key
isReservedProp
: 判斷是否是保留屬性
isBuiltInDirective
: 判斷是否是內(nèi)置指令
camelize
: 將字符串轉(zhuǎn)換為駝峰
hyphenate
: 將字符串轉(zhuǎn)換為連字符
capitalize
: 將字符串首字母大寫
toHandlerKey
: 將字符串轉(zhuǎn)換為事件處理的key
hasChanged
: 判斷兩個(gè)值是否相等
invokeArrayFns
: 調(diào)用數(shù)組中的函數(shù)
def
: 定義對(duì)象的屬性
looseToNumber
: 將字符串轉(zhuǎn)換為數(shù)字
toNumber
: 將字符串轉(zhuǎn)換為數(shù)字
getGlobalThis
: 獲取全局對(duì)象
genPropsAccessExp
: 生成props
的訪問表達(dá)式
這其中有大部分和Vue2
的工具函數(shù)是一樣的,還有數(shù)據(jù)類型的判斷,使用的是同一種方式,因?yàn)橛辛酥?code>Vue2的閱讀經(jīng)驗(yàn),所以這次快速閱讀;而且這次是直接源碼,ts
版本的,不再處理成js
,所以直接閱讀ts
源碼。
export function makeMap(
str: string,
expectsLowerCase?: boolean
): (key: string) => boolean {
const map: Record<string, boolean> = Object.create(null)
const list: Array<string> = str.split(',')
for (let i = 0; i < list.length; i++) {
map[list[i]] = true
}
return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val]
}
makeMap
的源碼在同級(jí)目錄下的makeMap.ts
文件中,引入進(jìn)來之后直接使用export
關(guān)鍵字導(dǎo)出,實(shí)現(xiàn)方式和Vue2
的實(shí)現(xiàn)方式相同;
export const EMPTY_OBJ: { readonly [key: string]: any } = __DEV__
? Object.freeze({})
: {}
export const EMPTY_ARR = __DEV__ ? Object.freeze([]) : []
EMPTY_OBJ
和EMPTY_ARR
的實(shí)現(xiàn)方式和Vue2
的emptyObject
相同,都是使用Object.freeze
凍結(jié)對(duì)象,防止對(duì)象被修改;
export const NOOP = () => {}
和Vue2
的noop
實(shí)現(xiàn)方式相同,都是一個(gè)空函數(shù),移除了入?yún)ⅲ?/p>
/**
* Always return false.
*/
export const NO = () => false
和Vue2
的no
實(shí)現(xiàn)方式相同,都是一個(gè)返回false
的函數(shù),移除了入?yún)ⅲ?/p>
const onRE = /^on[^a-z]/
export const isOn = (key: string) => onRE.test(key)
判斷是否是on
開頭的事件,并且on
后面的第一個(gè)字符不是小寫字母;
export const isModelListener = (key: string) => key.startsWith('onUpdate:')
判斷是否是onUpdate:
開頭的字符串;
參考:startWith
export const extend = Object.assign
直接擁抱es6
的Object.assign
,Vue2
的實(shí)現(xiàn)方式是使用for in
循環(huán);
export const remove = <T>(arr: T[], el: T) => {
const i = arr.indexOf(el)
if (i > -1) {
arr.splice(i, 1)
}
}
對(duì)比于Vue2
刪除了一些代碼,之前的快速刪除最后一個(gè)元素的判斷不見了;
猜測可能是因?yàn)橛?code>bug,因?yàn)榇蠹叶贾?code>Vue2的數(shù)組響應(yīng)式必須使用Array
的api
,那樣操作可能會(huì)導(dǎo)致數(shù)組響應(yīng)式失效;
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
相同;
export const isArray = Array.isArray
使用的是Array.isArray
,和Vue2
相同;
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 isDate = (val: unknown): val is Date =>
toTypeString(val) === '[object Date]'
export const isRegExp = (val: unknown): val is RegExp =>
toTypeString(val) === '[object RegExp]'
都是使用Object.toString
來判斷類型,對(duì)比于Vue2
新增了isMap
和isSet
和isDate
,實(shí)現(xiàn)方式?jīng)]變;
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'
和Vue2
的實(shí)現(xiàn)方式相同,都是使用typeof
來判斷類型,新增了isSymbol
;
export const isPromise = <T = any>(val: unknown): val is Promise<T> => {
return isObject(val) && isFunction(val.then) && isFunction(val.catch)
}
和Vue2
對(duì)比修改了實(shí)現(xiàn)方式,但是判斷邏輯沒變;
export const objectToString = Object.prototype.toString
直接是Object.prototype.toString
;
export const toTypeString = (value: unknown): string =>
objectToString.call(value)
對(duì)入?yún)?zhí)行Object.prototype.toString
;
export const toRawType = (value: unknown): string => {
// extract "RawType" from strings like "[object RawType]"
return toTypeString(value).slice(8, -1)
}
和Vue2
的實(shí)現(xiàn)方式相同;
export const isPlainObject = (val: unknown): val is object =>
toTypeString(val) === '[object Object]'
和Vue2
的實(shí)現(xiàn)方式相同;
export const isIntegerKey = (key: unknown) =>
isString(key) &&
key !== 'NaN' &&
key[0] !== '-' &&
'' + parseInt(key, 10) === key
判斷一個(gè)字符串是不是由一個(gè)整數(shù)組成的;
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
生成一個(gè)對(duì)象,用于判斷入?yún)⑹欠袷莾?nèi)部保留的屬性;
export const isBuiltInDirective = /*#__PURE__*/ makeMap(
'bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo'
)
使用makeMap
生成一個(gè)對(duì)象,用于判斷入?yún)⑹欠袷莾?nèi)置的指令;
const cacheStringFunction = <T extends (str: string) => string>(fn: T): T => {
const cache: Record<string, string> = Object.create(null)
return ((str: string) => {
const hit = cache[str]
return hit || (cache[str] = fn(str))
}) as T
}
同Vue2
的cached
相同,用于緩存字符串;
const camelizeRE = /-(\w)/g
/**
* @private
*/
export const camelize = cacheStringFunction((str: string): string => {
return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))
})
將-
連接的字符串轉(zhuǎn)換為駝峰式,同Vue2
的camelize
相同;
const hyphenateRE = /\B([A-Z])/g
/**
* @private
*/
export const hyphenate = cacheStringFunction((str: string) =>
str.replace(hyphenateRE, '-$1').toLowerCase()
)
將駝峰式字符串轉(zhuǎn)換為-
連接的字符串,同Vue2
的hyphenate
相同;
/**
* @private
*/
export const capitalize = cacheStringFunction(
(str: string) => str.charAt(0).toUpperCase() + str.slice(1)
)
將字符串首字母大寫,同Vue2
的capitalize
相同;
/**
* @private
*/
export const toHandlerKey = cacheStringFunction((str: string) =>
str ? `on${capitalize(str)}` : ``
)
將字符串首字母大寫并在前面加上on
;
// 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
;
export const invokeArrayFns = (fns: Function[], arg?: any) => {
for (let i = 0; i < fns.length; i++) {
fns[i](arg)
}
}
批量調(diào)用傳遞過來的函數(shù)列表,如果有參數(shù),會(huì)將參數(shù)傳遞給每個(gè)函數(shù);
export const def = (obj: object, key: string | symbol, value: any) => {
Object.defineProperty(obj, key, {
configurable: true,
enumerable: false,
value
})
}
使用Object.defineProperty
定義一個(gè)屬性,并使這個(gè)屬性不可枚舉;
/**
* "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
}
將字符串轉(zhuǎn)換為數(shù)字,如果轉(zhuǎn)換失敗,返回原字符串;
通過注釋知道主要用于v-model
的.number
修飾符;
/**
* 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
}
將字符串轉(zhuǎn)換為數(shù)字,如果轉(zhuǎn)換失敗,返回原數(shù)據(jù);
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
: {})
)
}
獲取全局對(duì)象,根據(jù)環(huán)境不同返回的對(duì)象也不同;
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
的訪問表達(dá)式,如果name
是合法的標(biāo)識(shí)符,直接返回__props.name
,否則返回通過JSON.stringify
轉(zhuǎn)換后的__props[name]。
到此,相信大家對(duì)“Vue3 shared模塊下的工具函數(shù)有哪些”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。