接下来看看下面这个 else if(isPlainObject(props)) ,这里的 isPlainObject 函数实际就是返回 props 的值是否为 object , isPlainObject 函数的具体实现我们也在后面分析。
else if (isPlainObject(props)) {
for (const key in props) {
val = props[key] name = camelize(key)
res[name] = isPlainObject(val)
? val
: { type: val }
}
}
使用 for…in 遍历props对象,和上面一样使用 camelize 函数将 ‘-‘ 转换为驼峰。这里有个三目运算:
res[name] = isPlainObject(val) ? val : { type: val }判断了一下 val 如果是 object ,那么在res对象上面添加一个为name变量的属性,并且将该属性的值设置为val。这个其实就是处理下面这种props的写法:
props: {
// 对象形式
id: {
type: Number,
required: true
}
}
如果 val 不是 object ,那么也在res对象上面添加一个为name变量的属性,并且将该属性的值设置为{ type: val }。这个其实就是处理下面这种props的写法:
props: {
// 基础的类型检查
name: String,
// 多个可能的类型
value: [String, Number],
}
经过处理后props会变成了下面这样:
props: {
name: {
type: String
},
value: {
type: [String, Number] }
}
所以不管我们使用vue提供的 props 哪种写法,最终vue都会帮我们转换成下面这种类型:
props: {
name: {
...,
type: '类型'
}
}
接下来看看上面提到的util函数 isPlainObject ,先把源码贴出来。
const _toString = Object.prototype.toStringexport function isPlainObject (obj: any): boolean {
return _toString.call(obj) === '[object Object]'
}
其实 Object.prototype.toString.call(obj) 的值为obj对象的类型。例如:
Object.prototype.toString.call({a: 1}) // [object Object]Object.prototype.toString.call(new Date) // [object Date]Object.prototype.toString.call([1]) // [object Array]Object.prototype.toString.call(null) // [object Null]接下来看看上面提到的util函数 camelize ,还是先把源码贴出来。
export function cached<F: Function> (fn: F): F {
const cache = Object.create(null)
return (function cachedFn (str: string) {
const hit = cache[str] return hit || (cache[str] = fn(str))
}: any)
}const camelizeRE = /-(w)/g










