【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)
})
原文地址:https://www.cnblogs.com/vickylinj/p/13674022.html