Vue 3 源码阅读流程

2,868 阅读2分钟

Vue3的三大核心功能模块

  • 1、Compiler模块:编译模板系统;

  • 2、Runtime模块:也可以称之为Renderer模块,真正渲染的模块;

  • 3、Reactivity模块:响应式系统;比如:data中数据, setup中数据

源码主要模块.png

在进行源码阅读的时候,给大家推荐一个插件Bookmarks,可直接编译器插件中直接搜索安装。方便阅读~ 关于Vue3源码,建议大家多理解patch函数 哈哈

三大系统协调工作

编译系统

将template模块转为render函数

渲染系统

runtime-dom以及runtime-core一系列业务逻辑的处理

响应式系统

主要进行vnode的diff算法

三大系统协调工作.png

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

CreateApp-创建流程

step1-创建render

在runtime-dom/src/index.ts文件中

1、通过ensureRenderer()函数创建 renderer

2、在renderer.ts文件中,通过baseCreateRenderer函数的实现体

3、在patch函数(约2千行) 最终返回render,并且返回一个createApp方法 createApp.png

CreateApp-断点调试流程

可以按照此步骤进行断点调试帮助理解

creatApp入口.png

Mount-挂载流程

step1-调用app对象里面的mount方法

这里其实就是调用apiCreateApp.ts文件中createAppAPI函数

1、返回了一个createApp函数

2、在CreateApp函数中定义了一个app对象

3、调用createApp返回的app对象里面的mount方法

mount-step0.png

step2-执行render函数

通过render函数将根组件挂载到DOM上面

mount-step1.png

step3-挂载Component

mountComponent函数主要做了三步操作

1、createComponentInstance函数初始化组件实例

    const instance: ComponentInternalInstance =

    compatMountInstance ||

    (initialVNode.component = createComponentInstance(

    initialVNode,

    parentComponent,

    parentSuspense

    ))

2、函数组件初始化过程真正给instance 内部状态赋值的方法,初始化组件内容

  setupComponent(instance)

3、监听组件数据的变化,并完成响应式

    setupRenderEffect(

    instance,

    initialVNode,

    container,

    anchor,

    parentSuspense,

    isSVG,

    optimized

    )

mount-step2.png

mount的完成流程

mount-all.png

debug断点调试mount流程

mount-step4.png

Compile 过程

step1-template模板转化成render函数

compile的目的是将template模板转化成render函数

compile编译过程.png

compile编译过程-0.png