vue3学习源码笔记(小白入门系列)------ 组件是如何渲染成dom挂载到指定位置的?

news/2024/10/18 10:27:07/

文章目录

    • os
    • 准备
      • 组件如何被挂载到页面上
        • 第一步 createApp 做了哪些工作?
          • ensureRenderer
          • baseCreateRenderer
          • createAppAPI
          • mount
          • render
          • patch
          • processComponent
          • processElement
      • 总结


os

学习一下vue3 源码,顺便记录分享下

使用vitest 插件调试源码 辅助阅读

准备

去 github 下载 vue3源码 最新仓库名 为 core-main 使用 版本 为3.3.4
在这里插入图片描述

安装好依赖 
npm i pnpm -g pnpm install

vscode 准备两个插件 方便代码调试
在这里插入图片描述

在这里插入图片描述
安装后会出现调试icon 未生效 可以重启vscode 。

在这里插入图片描述
代码打上 断点, 开启debug 调试

在这里插入图片描述

1 跳到下一个方法体
2 逐步执行
3 回退到上一步
4 重新执行
最后一个按钮就是 结束执行

组件如何被挂载到页面上

createApp(App).mount('#app')

第一步 createApp 做了哪些工作?

先看下入参和出参

export type CreateAppFunction<HostElement> = (rootComponent: Component,rootProps?: Data | null
) => App<HostElement> 入参: rootComponent 需要渲染的组件 App 也就是我们编写的 App.vue 文件rootProps 传入根实例 的 props 最后会被 挂在 app _props 上
出参 : 返回app 实例对象
// packages/runtime-dom/src/index.ts
export const createApp = ((...args) => {// 调用 ensureRender 生成render 对象 const render = ensureRenderer()// 再调用 render中 createApp 方法 来生成 app实例 const app = render.createApp(...args)···· 下面先省略return app
})
ensureRenderer
// packages/runtime-dom/src/renderer.ts
// 实际调用的是 createRenderer
function ensureRenderer() {
/*
大致意思是 判断renderer实例是否存在,有就直接返回 
没有执行 createRender 方法并 赋值 renderer 再返回  
这里返回的 renderer 对象,可以认为是一个跨平台的渲染器对象,
针对不同的平台,会创建出不同的 renderer 对象,
上述是创建浏览器环境的 renderer 对象,对于服务端渲染的场景,
则会创建 server render 的 renderer*/return (renderer ||(renderer = createRenderer<Node, Element | ShadowRoot>(rendererOptions)))
}// 实际调用 baseCreateRenderer
function createRenderer<HostNode = RendererNode,HostElement = RendererElement
>(options: RendererOptions<HostNode, HostElement>) {return baseCreateRenderer<HostNode, HostElement>(options)
}
baseCreateRenderer

有两种模式 hydration 模式是 服务端渲染的 我们只考虑 no-hydration 浏览器渲染
在这里插入图片描述
no-hydration 下
入参: options 初始化 渲染的参数

在这里插入图片描述

出参 :render  export interface Renderer<HostElement = RendererElement> {render: RootRenderFunction<HostElement>createApp: CreateAppFunction<HostElement>
}

具体伪代码 实现
// packages/runtime-core/src/renderer.ts
export function createRenderer(options) {// ...// 这里不介绍 hydrate 模式return {render,hydrate, // no-hydration 为空createApp: createAppAPI(render, hydrate),}
}

在这里插入图片描述

createAppAPI
// packages/runtime-core/src/apiCreateApp.ts
function createAppAPI(render, hydrate) {// createApp createApp 方法接收的两个参数:根组件的对象和 propreturn function createApp(rootComponent, rootProps = null) {// 。。。 省略const app = {// ... 省略很多不需要在这里介绍的属性_component: rootComponent,_props: rootProps,mount(rootContainer, isHydrate, isSVG) {// ...}}return app}
}

Vue 3 初始化根组件的核心方法,也就是入口文件 createApp 真正执行的内容就是这里的 createAppAPI 函数中的 createApp 函数,该函数接收了 组件作为根组件 rootComponent,返回了一个包含 mount 方法的 app 对象,再看看 mount 具体实现

mount
// packages/runtime-core/src/apiCreateApp.ts
mount(rootContainer, isHydrate, isSVG) {if (!isMounted) {// ... 省略部分不重要的代码// 1. 创建根组件的 vnodeconst vnode = createVNode(rootComponent,rootProps)// 2. 渲染根组件  这里render方法 其实是baseCreateRenderer // 返回的render对象带的 render方法 // 作用就是 将 vnode 渲染成真实domrender(vnode, rootContainer, isSVG)isMounted = true}
}
render
// packages/runtime-core/src/renderer.ts
const render: RootRenderFunction = (vnode, container, isSVG) => {// console.log('render-----');//第一个 入参 没传 代表 需要卸载 if (vnode == null) {if (container._vnode) {unmount(container._vnode, null, null, true)}} else {// 否则走 挂载 或更新 操作patch(container._vnode || null, vnode, container, null, null, null, isSVG)}flushPreFlushCbs()flushPostFlushCbs()container._vnode = vnode}
// patch  所有vnode diff 比对 更新 转化新dom 操作全在里面
patch
const patch: PatchFn = (n1, //  需要 对比的 旧 vnoden2, // 新生成的 vnode container, // 最后生成的元素 需要挂载到的 目标组件元素anchor = null, // 挂载的参考元素;parentComponent = null, // 父组件parentSuspense = null,isSVG = false,slotScopeIds = null,optimized = __DEV__ && isHmrUpdating ? false : !!n2.dynamicChildren) => {//n1 n2 完全一致 就 直接返回 不做更新 或 挂载if (n1 === n2) {return}// patching & not same type, unmount old tree  新旧 vnode  类型 不一样 直接 卸载 n1 if (n1 && !isSameVNodeType(n1, n2)) {anchor = getNextHostNode(n1)unmount(n1, parentComponent, parentSuspense, true)n1 = null}if (n2.patchFlag === PatchFlags.BAIL) {optimized = falsen2.dynamicChildren = null}// shapeFlag 判断vnode 实例是什么类型 有的是元素类型 函数类型 组件类型等const { type, ref, shapeFlag } = n2switch (type) {//文本节点case Text:processText(n1, n2, container, anchor)break// 注释节点case Comment:processCommentNode(n1, n2, container, anchor)breakcase Static:if (n1 == null) {mountStaticNode(n2, container, anchor, isSVG)} else if (__DEV__) {patchStaticNode(n1, n2, container, isSVG)}breakcase Fragment:// 处理 template 的虚拟标签processFragment(n1,n2,container,anchor,parentComponent,parentSuspense,isSVG,slotScopeIds,optimized)breakdefault:// 其它类型//ShapeFlags 是一个二进制左移操作符生成的对象if (shapeFlag & ShapeFlags.ELEMENT) {// 这里走的是 组件内部元素普通dom的比对更新挂载逻辑processElement(n1,n2,container,anchor,parentComponent,parentSuspense,isSVG,slotScopeIds,optimized)} else if (shapeFlag & ShapeFlags.COMPONENT) {// 这里是 组件对比 component 逻辑 processComponent(n1,n2,container,anchor,parentComponent,parentSuspense,isSVG,slotScopeIds,optimized)} 。。。 // 其它省略// set refif (ref != null && parentComponent) {/*通过 ref 参数获取组件的引用对象。通过 n1 参数获取前一个 VNode 的引用对象(如果存在)。通过 n2 参数获取当前 VNode 的引用对象(如果存在)。如果前一个 VNode 的引用对象存在(即 n1.ref 存在),则将其置为 null,解除对前         一个组件引用的绑定。如果当前 VNode 的引用对象存在(即 n2.ref 存在),则将其绑定到组件的引用上。如果当前 VNode 不存在(即 !n2),则将组件的引用对象置为 null*/setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2)}}

初始化挂载 会进入到 processComponent方法

processComponent
// packages/runtime-core/src/renderer.ts
function processComponent(n1, n2, container, parentComponent) {// 如果 n1 没有值的话,那么就是 mountif (!n1) {// 初始化 componentmountComponent(n2, container, parentComponent);} else {updateComponent(n1, n2, container);}
}// packages/runtime-core/src/renderer.ts
function mountComponent(initialVNode, container, parentComponent) {// 1. 先创建一个 component instance const instance = (initialVNode.component = createComponentInstance(initialVNode,parentComponent));// 2. 初始化 instance 上的 props, slots, 执行组件的 setup 函数...setupComponent(instance);// 3. 设置并运行带副作用的渲染函数setupRenderEffect(instance, initialVNode, container);
}// packages/runtime-core/src/component.ts
function createComponentInstance(vnode: VNode,parent: ComponentInternalInstance | null,suspense: SuspenseBoundary | null
) {const type = vnode.type as ConcreteComponent// inherit parent app context - or - if root, adopt from root vnodeconst appContext =(parent ? parent.appContext : vnode.appContext) || emptyAppContextconst instance: ComponentInternalInstance = {uid: uid++,vnode,type,parent,appContext,root: null!, // to be immediately setnext: null,subTree: null!, // will be set synchronously right after creationeffect: null!,update: null!, // will be set synchronously right after creationscope: new EffectScope(true /* detached */),render: null,proxy: null,//。。。 省略 属性}if (__DEV__) {instance.ctx = createDevRenderContext(instance)} else {instance.ctx = { _: instance }}instance.root = parent ? parent.root : instanceinstance.emit = emit.bind(null, instance)// apply custom element special handlingif (vnode.ce) {vnode.ce(instance)}return instance
}// packages/runtime-core/src/component.ts
export function setupComponent(instance) {// 1. 处理 props// 取出存在 vnode 里面的 props const { props, children } = instance.vnode;initProps(instance, props);// 2. 处理 slotsinitSlots(instance, children);// 3. 调用 setup 并处理 setupResultsetupStatefulComponent(instance);
}// packages/runtime-core/src/renderer.ts
/*
componentUpdateFn 这个函数,
核心是调用了 renderComponentRoot 来生成 subTree,
然后再把 subTree 挂载到 container 中
*/
const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {function componentUpdateFn() {if (!instance.isMounted) {// 渲染子树的 vnodeconst subTree = (instance.subTree = renderComponentRoot(instance))// 挂载子树 vnode 到 container 中 // 会重新进入 patch 方法 会走到 processElement 方法中patch(null, subTree, container, anchor, instance, parentSuspense, isSVG)// 把渲染生成的子树根 DOM 节点存储到 el 属性上initialVNode.el = subTree.elinstance.isMounted = true}else {// 更新相关,后面介绍}}// 创建副作用渲染函数instance.update = effect(componentUpdateFn, prodEffectOptions)
}/*
返回 vnode
*/
function renderComponentRoot(instance: ComponentInternalInstance
): VNode {const {type: Component,vnode,proxy,withProxy,props,propsOptions: [propsOptions],slots,attrs,emit,render,renderCache,data,setupState,ctx,inheritAttrs} = instanceconst proxyToUse = withProxy || proxy// 省略一部分逻辑判断 normalizeVNode 
/*render 方法 其实是调用instance.render 方法 就是在 初始化instance 方法 中 将 template 模版 编译成 render 方法 用于 生成  vnode
*/result = normalizeVNode(render!.call(proxyToUse,proxyToUse!,renderCache,props,setupState,data,ctx))return result 
}
processElement
// packages/runtime-core/src/renderer.ts
function processElement(n1, n2, container, anchor, parentComponent) {if (!n1) {// 挂载元素节点mountElement(n2, container, anchor);} else {// 更新元素节点updateElement(n1, n2, container, anchor, parentComponent);}
}// packages/runtime-core/src/renderer.ts
const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {let elconst { type, props, shapeFlag, transition, patchFlag, dirs } = vnode// ...// 根据 vnode 创建 DOM 节点el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is)if (props) {// 处理 props 属性for (const key in props) {if (!isReservedProp(key)) {hostPatchProp(el, key, null, props[key], isSVG)}}}// 文本节点处理if (shapeFlag & ShapeFlags.TEXT_CHILDREN) {hostSetElementText(el, vnode.children)} else if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {// 如果节点是个数据类型,则递归子节点mountChildren(vnode.children, el)}// 把创建好的 el 元素挂载到容器中hostInsert(el, container, anchor)
}

总结

以上就完成了 组件初始化工作。下面画了 几个流程图来辅助理解 。最好阅读的时候自己 也可以画下

安利一个好用的vscode流程图插件
在这里插入图片描述

请添加图片描述

下一篇:准备写 数据代理这块


http://www.ppmy.cn/news/1063038.html

相关文章

Vue学习之Vue组件的核心概念

组件是什么 vue组件就是一个个独立的小型的ui模块&#xff0c;整个大型的系统就是由一个个小型的UI模块拼接而成的 vue组件就是vue实例&#xff0c;通过new Vue函数来创建的一个vue实例&#xff0c;不同的组件只不过是options的不同&#xff0c;我们基本百分之90的开发工作都…

C# Winfrom通过COM接口访问和控制Excel应用程序,将Excel数据导入DataGridView

1.首先要创建xlsx文件 2.在Com中添加引用 3. 添加命名空间 using ApExcel Microsoft.Office.Interop.Excel; --这样起个名字方面后面写 4.样例 //点击操作excelDataTable dt new DataTable();string fileName "D:\desktop\tmp\test.xlsx";ApExcel.Application exA…

【C语言每日一题】04. 输出保留3位小数的浮点数

题目来源&#xff1a;http://noi.openjudge.cn/ch0101/04/ 01 输出保留3位小数的浮点数 总时间限制: 1000ms 内存限制: 65536kB 问题描述 读入一个单精度浮点数&#xff0c;保留3位小数输出这个浮点数。 输入 只有一行&#xff0c;一个单精度浮点数。 输出 也只有一行&am…

leetcode1475. 商品折扣后的最终价格 【单调栈】

简单题 第一次错误做法 class Solution { public:vector<int> finalPrices(vector<int>& prices) {int n prices.size();stack<int> st;unordered_map<int, int> mp;int i 0;while(i ! prices.size()) {int t prices[i];if (st.empty() || t …

使用CSS的@media screen 规则为不同的屏幕尺寸设置不同的样式(响应式图片布局)

当你想要在不同的屏幕尺寸或设备上应用不同的CSS样式时&#xff0c;可以使用 media 规则&#xff0c;特别是 media screen 规则。这允许你根据不同的屏幕特性&#xff0c;如宽度、高度、方向等&#xff0c;为不同的屏幕尺寸设置不同的样式。 具体来说&#xff0c;media screen…

算法通关村——数论经典问题解析

1. 辗转相除法 主要目的是获取两个数里面的最大公约数。 public int gcd(int a, int b) {int k 0;do {k a % b;a b;b k;} while (k ! 0);return a;}2. 素数和合数 素数的要求是必须大于等于2&#xff0c;并且只能被1和它本身整除。 判断的方法比较简单&#xff0c;就是从…

代码随想录第六十天

代码随想录第六十天 Leetcode 84. 柱状图中最大的矩形 Leetcode 84. 柱状图中最大的矩形 题目链接: 柱状图中最大的矩形 自己的思路:没想到&#xff01;&#xff01; 正确思路:和接雨水类似&#xff0c;只是需要左右补0&#xff01;&#xff01;&#xff01; 代码: class S…

macbookpro如何清理系统数据 macbookpro怎么删除软件

Macbook Pro是苹果公司的一款高性能笔记本电脑&#xff0c;它拥有强大的硬件和流畅的操作系统。然而&#xff0c;随着时间的推移&#xff0c;你可能会发现你的Macbook Pro变得越来越慢&#xff0c;储存空间也越来越紧张。这时候&#xff0c;你需要对你的Macbook Pro进行一些清理…