開發過程中,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 }}
新聞熱點
疑難解答
圖片精選