溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Vue3 shared模塊下的工具函數(shù)有哪些

發(fā)布時(shí)間:2022-12-13 09:43:53 來源:億速云 閱讀:315 作者:iii 欄目:編程語言

本篇內(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ū)別。

所有工具函數(shù)

  • 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源碼。

正式開始

makeMap

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)方式相同;

EMPTY_OBJ & EMPTY_ARR

export const EMPTY_OBJ: { readonly [key: string]: any } = __DEV__
  ? Object.freeze({})
  : {}
export const EMPTY_ARR = __DEV__ ? Object.freeze([]) : []

EMPTY_OBJEMPTY_ARR的實(shí)現(xiàn)方式和Vue2emptyObject相同,都是使用Object.freeze凍結(jié)對(duì)象,防止對(duì)象被修改;

NOOP

export const NOOP = () => {}

Vue2noop實(shí)現(xiàn)方式相同,都是一個(gè)空函數(shù),移除了入?yún)ⅲ?/p>

NO

/**
 * Always return false.
 */
export const NO = () => false

Vue2no實(shí)現(xiàn)方式相同,都是一個(gè)返回false的函數(shù),移除了入?yún)ⅲ?/p>

isOn

const onRE = /^on[^a-z]/
export const isOn = (key: string) => onRE.test(key)

判斷是否是on開頭的事件,并且on后面的第一個(gè)字符不是小寫字母;

isModelListener

export const isModelListener = (key: string) => key.startsWith('onUpdate:')

判斷是否是onUpdate:開頭的字符串;

參考:startWith

extend

export const extend = Object.assign

直接擁抱es6Object.assign,Vue2的實(shí)現(xiàn)方式是使用for in循環(huán);

remove

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)式必須使用Arrayapi,那樣操作可能會(huì)導(dǎo)致數(shù)組響應(yīng)式失效;

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<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新增了isMapisSetisDate,實(shí)現(xiàn)方式?jīng)]變;

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<any, any> =>
  val !== null && typeof val === 'object'

Vue2的實(shí)現(xiàn)方式相同,都是使用typeof來判斷類型,新增了isSymbol;

isPromise

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)方式,但是判斷邏輯沒變;

objectToString

export const objectToString = Object.prototype.toString

直接是Object.prototype.toString;

toTypeString

export const toTypeString = (value: unknown): string =>
  objectToString.call(value)

對(duì)入?yún)?zhí)行Object.prototype.toString

toRawType

export const toRawType = (value: unknown): string => {
  // extract "RawType" from strings like "[object RawType]"
  return toTypeString(value).slice(8, -1)
}

Vue2的實(shí)現(xiàn)方式相同;

isPlainObject

export const isPlainObject = (val: unknown): val is object =>
  toTypeString(val) === '[object Object]'

Vue2的實(shí)現(xiàn)方式相同;

isIntegerKey

export const isIntegerKey = (key: unknown) =>
  isString(key) &&
  key !== 'NaN' &&
  key[0] !== '-' &&
  '' + parseInt(key, 10) === key

判斷一個(gè)字符串是不是由一個(gè)整數(shù)組成的;

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生成一個(gè)對(duì)象,用于判斷入?yún)⑹欠袷莾?nèi)部保留的屬性;

isBuiltInDirective

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)置的指令;

cacheStringFunction

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
}

Vue2cached相同,用于緩存字符串;

camelize

const camelizeRE = /-(\w)/g
/**
 * @private
 */
export const camelize = cacheStringFunction((str: string): string => {
  return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))
})

-連接的字符串轉(zhuǎn)換為駝峰式,同Vue2camelize相同;

capitalize

const hyphenateRE = /\B([A-Z])/g
/**
 * @private
 */
export const hyphenate = cacheStringFunction((str: string) =>
  str.replace(hyphenateRE, '-$1').toLowerCase()
)

將駝峰式字符串轉(zhuǎn)換為-連接的字符串,同Vue2hyphenate相同;

capitalize

/**
 * @private
 */
export const capitalize = cacheStringFunction(
  (str: string) => str.charAt(0).toUpperCase() + str.slice(1)
)

將字符串首字母大寫,同Vue2capitalize相同;

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)
  }
}

批量調(diào)用傳遞過來的函數(shù)列表,如果有參數(shù),會(huì)將參數(shù)傳遞給每個(gè)函數(shù);

def

export const def = (obj: object, key: string | symbol, value: any) => {
  Object.defineProperty(obj, key, {
    configurable: true,
    enumerable: false,
    value
  })
}

使用Object.defineProperty定義一個(gè)屬性,并使這個(gè)屬性不可枚舉;

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
}

將字符串轉(zhuǎn)換為數(shù)字,如果轉(zhuǎ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
}

將字符串轉(zhuǎn)換為數(shù)字,如果轉(zhuǎn)換失敗,返回原數(shù)據(jù);

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
        : {})
  )
}

獲取全局對(duì)象,根據(jù)環(huán)境不同返回的對(duì)象也不同;

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的訪問表達(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í)!

向AI問一下細(xì)節(jié)

免責(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)容。

AI