【Vue】駝峰命名法和短橫線命名法的轉換以及Vue源碼中對駝峰式和大寫式查找的支持


駝峰命名:getElementById

短橫線命名:get-element-by-id

1、將駱駝命名規則的字符串轉換成使用短橫線命名法的字符串, 並且全小寫 .例如:'getElementById'=>'get-element-by-id'

正則表達式:

function getKebabCase( str ) {
    return str.replace( /[A-Z]/g, function( i ) {
        return '-' + i.toLowerCase();
    })
}
console.log( getKebabCase( 'getElementById' ) ); //get-element-by-id

采用數組的方法:

function getKebabCase ( str ) {
 var arr = str.split('');
    str = arr.map(function ( item ){
        if( item.toUpperCase() === item ){
            return '-' + item.toLowerCase();
        }else{
            return item;
        }
    }).join( '' );
    return str;
}
console.log( getKebabCase( 'getElementById' ) ); //get-element-by-id

2、將短橫線命名法的字符串轉換成使用駱駝命名規則的字符串, 並且全小寫 .例如:'get-element-by-id'=>'getElementById'

正則表達式:

function getCamelCase( str ) {
    return str.replace( /-([a-z])/g, function( all, i ){
        return i.toUpperCase();
    } )
}
console.log( getCamelCase( 'get-element-by-id' ) ); //getElementById

數組的方法:

function getCamelCase( str ) {
    var arr = str.split( '-' );
    return arr.map( function( item, index ) {
        if( index === 0 ){
            return item;
        }else{
            return item.charAt(0).toUpperCase() + item.slice( 1 );
        }
    }).join('');
}
console.log( getCamelCase( 'get-element-by-id' ) ); //getElementById

 3.Vue源碼中對駝峰式和大寫式查找的支持實現代碼如下:

src/core/util/options.js

export function resolveAsset (
  options: Object,
  type: string,
  id: string,
  warnMissing?: boolean
): any {
  /* istanbul ignore if */
  if (typeof id !== 'string') {
    return
  }
  const assets = options[type]
  // check local registration variations first
  if (hasOwn(assets, id)) return assets[id]
  const camelizedId = camelize(id)
  if (hasOwn(assets, camelizedId)) return assets[camelizedId]
  const PascalCaseId = capitalize(camelizedId)
  if (hasOwn(assets, PascalCaseId)) return assets[PascalCaseId]
  // fallback to prototype chain
  const res = assets[id] || assets[camelizedId] || assets[PascalCaseId]
  if (process.env.NODE_ENV !== 'production' && warnMissing && !res) {
    warn(
      'Failed to resolve ' + type.slice(0, -1) + ': ' + id,
      options
    )
  }
  return res
}

駝峰化:

/**
 * Camelize a hyphen-delimited string.
 */
const camelizeRE = /-(\w)/g
export const camelize = cached((str: string): string => {
  return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
})

大寫化:

/**
 * Capitalize a string.
 */
export const capitalize = cached((str: string): string => {
  return str.charAt(0).toUpperCase() + str.slice(1)
})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM