1. 程式人生 > 實用技巧 >vue原始碼中的檢測方法

vue原始碼中的檢測方法

// 判斷是否為undefined或null

const isDef = (v) => {
  return v !== undefined && v !== null
}

// 判斷是否為Promise函式

const isPromise = (val) => {
  return (
    val !== undefine &&
    typeof val.then === 'function' &&
    typeof val.catch === 'function'
  )
}

// 判斷是否為簡單資料型別

const isPrimitive (value) => {
  return (
    typeof value === 'string' ||
    typeof value === 'number' ||
    typeof value === 'symbol' ||
    typeof value === 'boolean'
  )
}

// 嚴格檢查複雜資料型別

const isPlainObject = (obj) => {
  return Object.prototype.toString.call(obj) === '[object Object]'
}

const isRegExp = (v) => {
  return Object.prototype.toString.call(v) === '[object RegExp]'
}

// 將駝峰字串轉成連線符 magicEightTall 轉換成 magic-eight-tall

const hyphenateRE = /\B([A-Z])/g
const hyphenate = (str) => {
  return str.replace(hyphenateRE, '-$1').toLowerCase()
}

// 將連線符轉成駝峰字串 magic-eight-tall 轉換成 magicEightTall

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

資源搜尋網站大全 https://www.renrenfan.com.cn 廣州VI設計公司https://www.houdianzi.com

// 如果不想重複轉換,可用以下方法呼叫轉換函式

const cached = (fn) => {
    const cache = Object.create(null)
    console.log(cache);
    return ((str) => {
      const hit = cache[str]
      return hit || (cache[str] = fn(str))
    })
};

// 例
const camelize = cached((str) => {
    return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
})