根据源码分析Vue 组件中 props的实现原理
整体功能概述
源码实现了一系列用于验证和处理组件 props 的工具函数,主要包括:
validateProp:验证单个prop的值,并处理默认值和类型转换。getPropDefaultValue:获取prop的默认值。assertProp:断言prop是否有效。assertType:检查值的类型是否符合预期。- 其他辅助函数,如
getType、isSameType等。
代码详细解释
1. 导入模块和类型定义
/* @flow */
import {
warn } from './debug'
import {
observe, toggleObserving, shouldObserve } from '../observer/index'
import {
hasOwn,
isObject,
toRawType,
hyphenate,
capitalize,
isPlainObject
} from 'shared/util'
type PropOptions = {
type: Function | Array<Function> | null,
default: any,
required: ?boolean,
validator: ?Function
};
/* @flow */:表示该文件使用 Flow 进行静态类型检查。- 导入了多个工具函数和模块,用于调试警告、响应式观察和一些通用工具方法。
PropOptions定义了prop的选项类型,包括type(类型)、default(默认值)、required(是否必需)和validator(自定义验证函数)。
2. validateProp 函数
export function validateProp (
key: string,
propOptions: Object,
propsData: Object,
vm?: Component
): any {
const prop = propOptions[key]
const absent = !hasOwn(propsData, key)
let value = propsData[key]
// boolean casting
const booleanIndex = getTypeIndex(Boolean, prop.type)
if (booleanIndex > -1) {
if (absent && !hasOwn(prop, 'default')) {
value = false
} else if (value === '' || value === hyphenate(key)) {
// only cast empty string / same name to boolean if
// boolean has higher priority
const stringIndex = getTypeIndex(String, prop.type)
if (stringIndex < 0 || booleanIndex < stringIndex) {
value = true
}
}
}
// check default value
if (value === undefined) {
value = getPropDefaultValue(vm, prop, key)
// since the default value is a fresh copy,
// make sure to observe it.
const prevShouldObserve = shouldObserve
toggleObserving(true)
observe(value)
toggleObserving(prevShouldObserve)
}
if (
process.env.NODE_ENV !== 'production' &&
// skip validation for weex recycle-list child component props
!(__WEEX__


2197

被折叠的 条评论
为什么被折叠?



