最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解Vue內部怎樣處理props選項的多種寫法

 更新時間:2018年11月06日 11:41:44   作者:邊城少年_  
這篇文章主要介紹了詳解Vue內部怎樣處理props選項的多種寫法,詳細的介紹了props的使用的寫法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

開發(fā)過程中,props 的使用有兩種寫法:

// 字符串數(shù)組寫法
const subComponent = {
 props: ['name']
}
// 對象寫法
const subComponent = {
 props: {
  name: {
   type: String,
   default: 'Kobe Bryant'
  }
 }
}

Vue在內部會對 props 選項進行處理,無論開發(fā)時使用了哪種語法,Vue都會將其規(guī)范化為對象的形式。具體規(guī)范方式見Vue源碼 src/core/util/options.js 文件中的 normalizeProps 函數(shù):

/**
 * Ensure all props option syntax are normalized into the
 * Object-based format.(確保將所有props選項語法規(guī)范為基于對象的格式)
 */
 // 參數(shù)的寫法為 flow(https://flow.org/) 語法
function normalizeProps (options: Object, vm: ?Component) {
 const props = options.props
 // 如果選項中沒有props,那么直接return
 if (!props) return
 // 如果有,開始對其規(guī)范化
 // 聲明res,用于保存規(guī)范化后的結果
 const res = {}
 let i, val, name
 if (Array.isArray(props)) {
  // 使用字符串數(shù)組的情況
  i = props.length
  // 使用while循環(huán)遍歷該字符串數(shù)組
  while (i--) {
   val = props[i]
   if (typeof val === 'string') {
    // props數(shù)組中的元素為字符串的情況
    // camelize方法位于 src/shared/util.js 文件中,用于將中橫線轉為駝峰
    name = camelize(val)
    res[name] = { type: null }
   } else if (process.env.NODE_ENV !== 'production') {
    // props數(shù)組中的元素不為字符串的情況,在非生產環(huán)境下給予警告
    // warn方法位于 src/core/util/debug.js 文件中
    warn('props must be strings when using array syntax.')
   }
  }
 } else if (isPlainObject(props)) {
  // 使用對象的情況(注)
  // isPlainObject方法位于 src/shared/util.js 文件中,用于判斷是否為普通對象
  for (const key in props) {
   val = props[key]
   name = camelize(key)
   // 使用for in循環(huán)對props每一個鍵的值進行判斷,如果是普通對象就直接使用,否則將其作為type的值
   res[name] = isPlainObject(val)
    ? val
    : { type: val }
  }
 } else if (process.env.NODE_ENV !== 'production') {
  // 使用了props選項,但它的值既不是字符串數(shù)組,又不是對象的情況
  // toRawType方法位于 src/shared/util.js 文件中,用于判斷真實的數(shù)據(jù)類型
  warn(
   `Invalid value for option "props": expected an Array or an Object, ` +
   `but got ${toRawType(props)}.`,
   vm
  )
 }
 options.props = res
}

如此一來,假如我的 props 是一個字符串數(shù)組:

props: ["team"]

經(jīng)過這個函數(shù)之后,props 將被規(guī)范為:

props: {
 team:{
  type: null
 }
}

假如我的 props 是一個對象:

props: {
 name: String,
 height: {
  type: Number,
  default: 198
 }
}

經(jīng)過這個函數(shù)之后,將被規(guī)范化為:

props: {
 name: {
  type: String
 },
 height: {
  type: Number,
  default: 198
 }
}

注:對象的寫法也分為以下兩種,故仍需進行規(guī)范化

props: {
 // 第一種寫法,直接寫類型
 name: String,
 // 第二種寫法,寫對象
 name: {
  type: String,
  default: 'Kobe Bryant'
 }
}

最終會被規(guī)范為第二種寫法。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論

怀集县| 长丰县| 锦州市| 理塘县| 土默特右旗| 安宁市| 页游| 新宁县| 白朗县| 腾冲县| 孙吴县| 吉木乃县| 德州市| 徐闻县| 弥渡县| 北辰区| 平泉县| 邯郸县| 黔东| 井研县| 南岸区| 凯里市| 延安市| 石林| 楚雄市| 佛山市| 安达市| 堆龙德庆县| 北川| 宁乡县| 横峰县| 大港区| 绿春县| 永嘉县| 焉耆| 宁海县| 扶风县| 马鞍山市| 浦江县| 祁东县| 青浦区|