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


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

// 字符串數組寫法
const subComponent = {
  props: [ 'name' ]
}
// 對象寫法
const subComponent = {
  props: {
   name: {
    type: String,
    default : 'Kobe Bryant'
   }
  }
}
 
 
 
Vue在內部會對 props 選項進行處理,無論開發時使用了哪種語法,Vue都會將其規范化為對象的形式。具體規范方式見 Vue源碼 src/core/util/options.js 文件中的 normalizeProps 函數:
/**
  * Ensure all props option syntax are normalized into the
  * Object-based format.(確保將所有props選項語法規范為基於對象的格式)
  */
  // 參數的寫法為 flow(https://flow.org/) 語法
function normalizeProps (options: Object, vm: ?Component) {
  const props = options.props
  // 如果選項中沒有props,那么直接return
  if (!props) return
  // 如果有,開始對其規范化
  // 聲明res,用於保存規范化后的結果
  const res = {}
  let i, val, name
  if (Array.isArray(props)) {
   // 使用字符串數組的情況
   i = props.length
   // 使用while循環遍歷該字符串數組
   while (i--) {
    val = props[i]
    if ( typeof val === 'string' ) {
     // props數組中的元素為字符串的情況
     // camelize方法位於 src/shared/util.js 文件中,用於將中橫線轉為駝峰
     name = camelize(val)
     res[name] = { type: null }
    } else if (process.env.NODE_ENV !== 'production' ) {
     // props數組中的元素不為字符串的情況,在非生產環境下給予警告
     // 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循環對props每一個鍵的值進行判斷,如果是普通對象就直接使用,否則將其作為type的值
    res[name] = isPlainObject(val)
     ? val
     : { type: val }
   }
  } else if (process.env.NODE_ENV !== 'production' ) {
   // 使用了props選項,但它的值既不是字符串數組,又不是對象的情況
   // toRawType方法位於 src/shared/util.js 文件中,用於判斷真實的數據類型
   warn(
    `Invalid value for option "props" : expected an Array or an Object, ` +
    `but got ${toRawType(props)}.`,
    vm
   )
  }
  options.props = res
}
 
 
 
如此一來,假如我的 props 是一個字符串數組:
props: [ "team" ]
經過這個函數之后,props 將被規范為:
props: {
  team:{
   type: null
  }
}
 
假如我的 props 是一個對象:
props: {
  name: String,
  height: {
   type: Number,
   default : 198
  }
}
 
經過這個函數之后,將被規范化為:
props: {
  name: {
   type: String
  },
  height: {
   type: Number,
   default : 198
  }
}
 
注:對象的寫法也分為以下兩種,故仍需進行規范化
props: {
  // 第一種寫法,直接寫類型
  name: String,
  // 第二種寫法,寫對象
  name: {
   type: String,
   default : 'Kobe Bryant'
  }
}

最終會被規范為第二種寫法。

原文地址 https://www.jb51.net/article/150255.htm

 


免責聲明!

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



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