您现在的位置是:网站首页> 编程资料编程资料
Template ref在Vue3中的实现原理详解_vue.js_
2023-05-24
361人已围观
简介 Template ref在Vue3中的实现原理详解_vue.js_
背景
最近我的 Vue3 音乐课程后台问答区频繁出现一个关于 Template ref 在 Composition API 中使用的问题,于是我就想写一篇文章详细解答这个问题。
先来看一个简单的例子:
This is a root element
首先我们在模板中给 div 添加了 ref 属性,并且它的值是 root 字符串,接下来我们在 setup 函数中使用 ref API 定义了一个 root 的响应式对象,并把它放到 setup 函数的返回对象中。
那么有小伙伴就问了,setup 函数中使用 ref API 定义的 root 和在模板中定义的 ref 是同一个东西吗?如果不是,那为什么需要同名呢,不同名可以吗?
带着这些疑问,我们来分析一下 Template ref 的实现原理。
模板的编译
我们还是结合示例来分析,首先借助于模板导出工具,可以看到它编译后的 render 函数:
import { openBlock as _openBlock, createElementBlock as _createElementBlock } from "vue" const _hoisted_1 = { ref: "root" } export function render(_ctx, _cache, $props, $setup, $data, $options) { return (_openBlock(), _createElementBlock("div", _hoisted_1, "This is a root element", 512 /* NEED_PATCH */)) } 可以看到,render 函数内部使用了 createElementBlock 函数来创建对应的元素 vnode,来看它实现:
function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) { return setupBlock(createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, true /* isBlock */)); } function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1 /* ELEMENT */, isBlockNode = false, needFullChildrenNormalization = false) { const vnode = { __v_isVNode: true, __v_skip: true, type, props, key: props && normalizeKey(props), ref: props && normalizeRef(props), scopeId: currentScopeId, slotScopeIds: null, children, component: null, suspense: null, ssContent: null, ssFallback: null, dirs: null, transition: null, el: null, anchor: null, target: null, targetAnchor: null, staticCount: 0, shapeFlag, patchFlag, dynamicProps, dynamicChildren: null, appContext: null } if (needFullChildrenNormalization) { normalizeChildren(vnode, children) if (shapeFlag & 128 /* SUSPENSE */) { type.normalize(vnode) } } else if (children) { vnode.shapeFlag |= isString(children) ? 8 /* TEXT_CHILDREN */ : 16 /* ARRAY_CHILDREN */ } // ... // 处理 Block Tree return vnode } 这里我们先不用管 Block 的相关逻辑,重点看 vnode 的创建过程。
createElementBlock 函数内部通过 createBaseVNode 函数来创建生成 vnode 对象,其中第二个参数 props 就是用来描述 vnode 的一些属性,在这个例子中 props 的值是 {ref: "root"}。
生成的 vnode 对象中,有一个 ref 属性,在 props 存在的情况下,会经过一层 normalizeRef 的处理:
const normalizeRef = ({ ref }) => { return (ref != null ? isString(ref) || isRef(ref) || isFunction(ref) ? { i: currentRenderingInstance, r: ref } : ref : null) } 至此,我们已知 div 标签在 render 函数执行之后转换成一个元素 vnode,它对应的 type 是 div,props 值是 {ref: "root"}、ref 的值是 {i: currentRenderingInstance, r: "root"}。
setup 函数返回值的处理
接下来,我们顺着组件的挂载过程,来分析 setup 函数的返回值是如何处理的。一个组件的挂载,首先会执行 mountComponent 函数:
const mountComponent = (initialVNode, container, anchor, parentComponent) => { // 创建组件实例 const instance = initialVNode.component = createComponentInstance(initialVNode, parentComponent) // 设置组件实例 setupComponent(instance) // 设置并运行带副作用的渲染函数 setupRenderEffect(instance, initialVNode, container, anchor) } 可以看到,mountComponent 主要做了三件事情:创建组件实例、设置组件实例和设置并运行带副作用的渲染函数。
其中 setup 函数的处理逻辑在 setupComponent 函数内部:
function setupComponent (instance, isSSR = false) { const { props, children, shapeFlag } = instance.vnode // 判断是否是一个有状态的组件 const isStateful = shapeFlag & 4 // 初始化 props initProps(instance, props, isStateful, isSSR) // 初始化 插槽 initSlots(instance, children) // 设置有状态的组件实例 const setupResult = isStateful ? setupStatefulComponent(instance, isSSR) : undefined return setupResult } setupComponent 内部会根据 shapeFlag 的值判断这是不是一个有状态组件,如果是则要进一步去设置有状态组件的实例。
通常我们写的组件就是一个有状态的组件,所谓有状态,指的就是组件在渲染过程中,会把它的一些状态挂载到组件实例对应的属性上。
接下来看 setupStatefulComponent 函数:
function setupStatefulComponent (instance, isSSR) { const Component = instance.type // 创建渲染代理的属性访问缓存 instance.accessCache = {} // 创建渲染上下文代理 instance.proxy = markRaw(new Proxy(instance.ctx, PublicInstanceProxyHandlers)) // 判断处理 setup 函数 const { setup } = Component if (setup) { // 如果 setup 函数带参数,则创建一个 setupContext const setupContext = (instance.setupContext = setup.length > 1 ? createSetupContext(instance) : null) // 执行 setup 函数,获取返回值 const setupResult = callWithErrorHandling(setup, instance, 0 /* SETUP_FUNCTION */, [instance.props, setupContext]) // 处理 setup 返回值 handleSetupResult(instance, setupResult) } else { // 完成组件实例设置 finishComponentSetup(instance) } } setupStatefulComponent 函数主要做了三件事:创建渲染上下文代理、判断处理 setup 函数和完成组件实例设置。
这里我们重点关注判断处理 setup 函数部分,首先它会通过 callWithErrorHandling 的方式来执行组件定义的 setup 函数,并把它的返回值放到 setupResult 中,然后执行 handleSetupResult 函数来处理 setup 执行结果,来看它的实现:
function handleSetupResult(instance, setupResult) { if (isFunction(setupResult)) { // setup 返回渲染函数 instance.render = setupResult } else if (isObject(setupResult)) { // 把 setup 返回结果做一层代理 instance.setupState = proxyRefs(setupResult) } finishComponentSetup(instance) } 可以看到,如果 setup 函数返回值是一个函数,那么该函数就作为组件的 render 函数;如果 setup 返回值是一个对象,那么则把它的值做一层代理,赋值给 instance.setupState。
组件的渲染
setupComponent 函数执行完,就要执行 setupRenderEffect 设置并运行带副作用的渲染函数,简化后的实现如下:
const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => { // 组件的渲染和更新函数 const componentUpdateFn = () => { if (!instance.isMounted) { // 渲染组件生成子树 vnode const subTree = (instance.subTree = renderComponentRoot(instance)) // 把子树 vnode 挂载到 container 中 patch(null, subTree, container, anchor, instance, parentSuspense, isSVG) // 保留渲染生成的子树根 DOM 节点 initialVNode.el = subTree.el instance.isMounted = true } else { // 更新组件 } } // 创建组件渲染的副作用响应式对象 const effect = new ReactiveEffect(componentUpdateFn, () => queueJob(instance.update), instance.scope) const update = (instance.update = effect.run.bind(effect)) update.id = instance.uid // 允许递归更新自己 effect.allowRecurse = update.allowRecurse = true update() } setupRenderEffect 函数内部利用响应式库的 ReactiveEffect 函数创建了一个副作用实例 effect,并且把 instance.update 函数指向了 effect.run。
当首次执行 instance.update 时,内部就会执行 componentUpdateFn 函数触发组件的首次渲染。
当组件的数据发生变化时,组件渲染函数 componentUpdateFn 会重新执行一遍,从而达到重新渲染组件的目的。
componentUpdateFn 函数内部会判断这是一次初始渲染还是组件的更新渲染,目前我们只需关注初始渲染流程。
初始渲染主要做两件事情:执行 renderComponentRoot 函数渲染组件生成 subTree 子树 vnode,执行 patch 函数把 subTree 挂载到 container 中。
renderComponentRoot 内部会执行组件的 render 函数渲染生成一棵 vnode 树,然后在 patch 过程中把 vnode 树渲染生成真正的 DOM 树。
接下来看 patch 函数的实现:
const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, slotScopeIds = null, optimized = false) => { const { type, ref, shapeFlag } = n2 switch (type) { case Text: // 处理文本节点 break case Comment: // 处理注释节点 break case Static: // 处理静态节点 break case Fragment: // 处理 Fragment 元素 break default: if (shapeFlag & 1 /* ELEMENT */) { // 处理普通 DOM 元素 processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) } else if (shapeFlag & 6 /* COMPONENT */) { // 处理组件 processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) } else if (shapeFlag & 64 /* TELEPORT */) { // 处理 TELEPORT } else if (shapeFlag & 128 /* SUSPENSE */) { // 处理 SUSPENSE } } // 设置 ref if (ref != null && parentComponent) { setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2) } } 在组件的首次渲染阶段,patch 函数内部会根据 vnode 节点类型的不同,执行不同的处理逻辑,最终目的就是构造出一棵 DOM 树。
Template Ref 的注册
遍历渲染 DOM 树的过程,实际上就是一个递归执行 patch 函数的过程,在 patch 函数的最后,也就是当前节点挂载后,会判断如果新的 vnode 存在 ref 属性,则执行 setRef 完成 Template Ref 的注册逻辑。
显然,对于我们示例来说,div 标签生成的元素 vnode,它对应的 ref 的值是 {i: currentRenderingInstance, r: "root"},满足条件,则会执行 setRef 函数,来看它的实现:
function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) { // 如果 rawRef 是数组,则遍历递归执行 setRef if (isArray(rawRef)) { rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode, isUnmount)) return } if (isAsyncWrapper(vnode) && !isUnmount) { return } // 如果 vnode 是组件 vnode,refValue 指向组件的实例,否则指向元素的 DOM const refValue = vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */ ? getExposeProxy(vnode.component) || vnode.component.proxy : vnode.el const value = isUnmount ? null : refValue const { i: owner, r: ref } = rawRef if ((process.env.NODE_ENV !== 'production') && !owner) { warn(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` + `A vnode with ref must be created inside the render function.`) return } const oldRef = oldRawRef && oldRawRef.r const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs const setupState = owner.setupState // ref 动态更新,删除旧的 if (oldRef != null && oldRef !== ref) { if (isString(oldRef)) { refs[oldRef] = null if (hasOwn(setupState, oldRef)) { setupState[oldRef] = null } } els
相关内容
- js实现一键换肤效果_javascript技巧_
- Vue.js和Vue.runtime.js区别浅析_vue.js_
- js复制文本到粘贴板(Clipboard.writeText())_javascript技巧_
- JavaScript中async和await的使用及队列详情_javascript技巧_
- JS实现一键复制_javascript技巧_
- 微信小程序自定义地址组件_javascript技巧_
- vue 为什么要封装全局组件引入_vue.js_
- Jquery实现下拉菜单案例_jquery_
- JS实现简单拖动模态框案例_javascript技巧_
- vue项目中一定会用到的性能优化技巧_vue.js_
点击排行
本栏推荐
