详解Vue内部怎样处理props选项的多种写法
开发过程中,props的使用有两种写法:
//字符串数组写法
constsubComponent={
props:['name']
}
//对象写法
constsubComponent={
props:{
name:{
type:String,
default:'KobeBryant'
}
}
}
Vue在内部会对props选项进行处理,无论开发时使用了哪种语法,Vue都会将其规范化为对象的形式。具体规范方式见Vue源码src/core/util/options.js文件中的normalizeProps函数:
/**
*Ensureallpropsoptionsyntaxarenormalizedintothe
*Object-basedformat.(确保将所有props选项语法规范为基于对象的格式)
*/
//参数的写法为flow(https://flow.org/)语法
functionnormalizeProps(options:Object,vm:?Component){
constprops=options.props
//如果选项中没有props,那么直接return
if(!props)return
//如果有,开始对其规范化
//声明res,用于保存规范化后的结果
constres={}
leti,val,name
if(Array.isArray(props)){
//使用字符串数组的情况
i=props.length
//使用while循环遍历该字符串数组
while(i--){
val=props[i]
if(typeofval==='string'){
//props数组中的元素为字符串的情况
//camelize方法位于src/shared/util.js文件中,用于将中横线转为驼峰
name=camelize(val)
res[name]={type:null}
}elseif(process.env.NODE_ENV!=='production'){
//props数组中的元素不为字符串的情况,在非生产环境下给予警告
//warn方法位于src/core/util/debug.js文件中
warn('propsmustbestringswhenusingarraysyntax.')
}
}
}elseif(isPlainObject(props)){
//使用对象的情况(注)
//isPlainObject方法位于src/shared/util.js文件中,用于判断是否为普通对象
for(constkeyinprops){
val=props[key]
name=camelize(key)
//使用forin循环对props每一个键的值进行判断,如果是普通对象就直接使用,否则将其作为type的值
res[name]=isPlainObject(val)
?val
:{type:val}
}
}elseif(process.env.NODE_ENV!=='production'){
//使用了props选项,但它的值既不是字符串数组,又不是对象的情况
//toRawType方法位于src/shared/util.js文件中,用于判断真实的数据类型
warn(
`Invalidvalueforoption"props":expectedanArrayoranObject,`+
`butgot${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:'KobeBryant'
}
}
最终会被规范为第二种写法。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。