16. 简化版 Ref 实现
16. 简化版 Ref 实现
简化版 Ref 实现,创建虚拟节点时获取 ref。
export function createVnode(type, props, children?) {
const shapeFlag = isString(type)
? ShapeFlags.ELEMENT // 元素
: isObject(type)
? ShapeFlags.STATEFUL_COMPONENT // 组件
: isFunction(type)
? ShapeFlags.FUNCTIONAL_COMPONENT
: 0;
const vnode = {
__v_isVnode: true,
type,
props,
children,
key: props?.key,
el: null,
shapeFlag,
ref: props && props.ref, // 提取ref
};
function setRef(rawRef, vnode) {
const refValue =
vnode.shapeFlag & ShapeFlags.STATEFUL_COMPONENT
? vnode.component.exposed || vnode.component!.proxy
: vnode.el;
if (rawRef) {
rawRef.value = refValue;
}
}
const patch = (n1, n2, container, anchor = null, parentComponent = null) => {
// ...
if (ref !== null) {
// 新ref 和 老ref
setRef(ref, n2);
}
};