Props 名为「道具」,当外部组件给内部组件传值时,通常在这个时候使用 props 。
export function setupComponent(
instance: ComponentInternalInstance,
isSSR = false
) {
//初始化 props
initProps(instance, props, isStateful, isSSR)
}
代码位置:runtime-core/src/component.ts
-
instance 组件实例; -
props 从 instance.vnode 解构出来的 props 数据,包括属性和动态属性; -
isStateful 是否是有状态组件; -
isSSR 是否是服务端渲染,默认为 false;
<tree-item class=\\\"item\\\" :model=\\\"treeData\\\"></tree-item>
export function initProps(
instance: ComponentInternalInstance,
rawProps: Data | null,
isStateful: number,
// result of bitwise flag comparison
isSSR = false
) {
// 先定义两个空数据
const props: Data = {}
const attrs: Data = {}
// 枚举属性设置成 false
def(attrs, InternalObjectKey, 1)
// 设置 props 值
setFullProps(instance, rawProps, props, attrs)
// 验证 props
if (__DEV__) { validateProps(props, instance) }
// 是否是状态组件,变成响应式的
instance.props = isSSR ? props : shallowReactive(props)
// 赋值给 instance.attrs
instance.attrs = attrs
}
function setFullProps(
instance: ComponentInternalInstance,
rawProps: Data | null,
props: Data,
attrs: Data
) {
//如果是 key 或者 ref 则退出此次循环
if (isReservedProp(key)) { continue }
let camelKey
//标准化 key 的命名为「驼峰样式」
if (options && hasOwn(options, (camelKey = camelize(key)))) {
props[camelKey] = value
} else if (!isEmitListener(instance.emitsOptions, key)) {
// 如果不是 Emit 相关,也不是 props ,那就保存到 attrs 里。
attrs[key] = value
}
// ...
if (needCastKeys) {
const rawCurrentProps = toRaw(props)
for (let i = 0; i < needCastKeys.length; i++) {
const key = needCastKeys[i]
props[key] = resolvePropValue(
options!,
rawCurrentProps,
key,
rawCurrentProps[key],
instance
)
}
}
}
代码位置:runtime-core/src/componentProps.ts
//是否必填
if (required && isAbsent) {
warn(\\\'Missing required prop: \\\"\\\' + name + \\\'\\\"\\\')
return
}
//是否通过验证
if (validator && !validator(value)) {
warn(\\\'Invalid prop: custom validator check failed for prop \\\"\\\' + name + \\\'\\\".\\\')
}
props: {
treeName: {
type: Number,
required: true,//是否必填
}
}
warn(\\\'Missing required prop: \\\"\\\' + name + \\\'\\\"\\\')
props: {
treeName: {
type: Number,
required: true,//是否必填
validator(val) {
return val >= 10
}
}
}
warn(\\\'Invalid prop: custom validator check failed for prop \\\"\\\' + name + \\\'\\\".\\\')
export function shallowReactive<T extends object>(target: T): T {
return createReactiveObject(
target,
false,
shallowReactiveHandlers,
shallowCollectionHandlers
)
}
instance.props = isSSR ? props : shallowReactive(props)
//...
instance.attrs = attrs
原创文章,作者:小道研究,如若转载,请注明出处:https://www.sudun.com/ask/34477.html