vue 构造函数的内容

81 阅读1分钟

构造函数 Vue() 所做的具体事情如下:

  • 创建 Vue 实例:创建一个新的 Vue 实例,并返回该实例。该函数位于 runtime-core/src/index.ts 中,方法名为 createApp。(其实是runtime-dom/src/index.t)

  • 初始化实例配置:将传入构造函数的配置选项保存在实例的 _options 属性中。该操作发生在 runtime-core/src/apiCreateApp.ts 中的 createApp 函数中。createAppAPI

  • 初始化实例属性:在实例上添加一些核心属性,用于处理组件数据、属性等。这包括 datadata、props、$attrs 等。该操作发生在 runtime-core/src/apiCreateApp.ts 中的 createApp 函数中。

    生成context和app对象

mount中调用render方法 =》processComponent =》mountComponent =》setupComponent =》finishComponentSetup=》 applyOptions =》 初始化实例生命周期钩子函数

  • 初始化实例生命周期钩子函数:为实例添加生命周期钩子函数,包括 beforeCreate、created、beforeMount、mounted、beforeUpdate、updated、beforeUnmount、unmounted 等。该操作发生在 runtime-core/src/apiLifecycle.ts 中。

  • 创建实例的事件系统:为实例创建事件系统,包括 onon、emit、offoff、once 等方法,用于组件间的通信。 mount中调用render方法 =》patch =》processElement =》patchElement => hostPatchProp

  • 创建实例的响应式系统:将实例的数据对象和属性进行响应式处理,使其能够实现数据驱动的视图更新。该操作发生在 reactivity/ 目录下的多个文件中,例如 reactivity/src/reactive.ts 和 reactivity/src/computed.ts。后面分析每个api源码

  • 创建实例的渲染函数:创建实例的 render 函数,用于根据数据和组件选项生成虚拟 DOM。该操作发生在 runtime-core/src/renderer.ts 中。从mount方法开始调用到这边的render函数

  • 创建虚拟 DOM:创建 h 函数,用于生成虚拟 DOM 节点,将其用于组件的渲染。该操作发生在 runtime-core/src/h.ts 中。 调用createVNode方法

  • 创建组件及指令系统:为实例创建组件和指令系统,用于组件的注册和使用。该操作发生在 runtime-core/src/component/index.ts 和 runtime-core/src/directives/index.ts 中。

以上提及的文件和方法名可能不完整,仅供参考。由于 Vue 3 源码结构及命名可能会随版本更新而变化,建议查阅 Vue 3 的官方文档和源码仓库以获取最准确的信息。