1. 首页
  2. 技术知识

vue3源码分析——实现组件的挂载流程

引言

<<往期回顾>>

    手写vue3源码——创建项目手写vue3源码——reactive, effect ,scheduler, stop手写vue3源码——readonly, isReactive,isReadonly, shallowReadonly手写vue3源码——ref, computedvue3源码分析——rollup打包monorepo

接下来一起学习下,runtime-core里面的方法,本期主要实现的内容是,
通过createAPP方法,到mount最后把咋们的dom给挂载成功!,所有的源码请查看


效果

咋们需要使这个测试用例跑成功!,在图中可以发现,调用app传入了一个render函数,然后挂载,对比期望结果!


测试dom

思考再三,先把这一节先说了,
jest是怎么来测试dom的?

jest默认的环境是node,在jest.config.js中可以看到

npm有在node中实现了浏览器环境的api的库,jsdom、happy-dom 等,咋们这里就使用比较轻的happy-dom,但是happy-dom里面与jest结合是一个子包——@happy-dom/jest-environment,那就安装一下

pnpm add @happy-dom/jest-environment -w -D复制代码

由于我项目示例使用的是monorepo,所以只需要在runtime-core中进行以下操作即可:

在jest.config.js中修改环境

testEnvironment: ‘@happy-dom/jest-environment’,复制代码

然后你就可以在当前子包中使用正确运行测试用例了。


小问题

    全局的package.json运行的时候报错,内容是没有dom环境
    vscode 插件 jest自动运行失败

针对第一个问题,在上一节vue3源码分析——rollup打包monorepo中我们可以知道,在全局可以执行packages中的每一个脚本,同理,我们做以下操作:

// 在全局的package.json中的test修改成这句话 “test”: “pnpm -r –filter=./packages/** run test”,复制代码

那么就可以执行啦!

第二个问题,这个是vscode的插件问题,我们可以重jest插件的文档入手,可以发现jest执行的时候,可以自定义脚本,解决办法如下:


意思是说,jest自动执行的时候,直接执行我们项目的test脚本,由于第一个问题的解决,第二个问题也是ok的哦!

正文


在正文之前,希望您先看过本系列文章的 vue3 组件初始化流程,这里详细介绍了组件的初始化流程,这里主要是实现挂载

测试用例

describe(‘apiCreateApp’, () => {// 定义一个跟节点  let appElement: Element;  // 开始之前创建dom元素  beforeEach(() => {    appElement = document.createElement(‘div’);    appElement.id = ‘app’;    document.body.appendChild(appElement);  });// 执行完测试后,情况html内部的内容  afterEach(() => {    document.body.innerHTML = ”;  });  test(‘测试createApp,是否正确挂载’, () => {  // 调用app方法,传入render函数    const app = createApp({      render() {        return h(‘div’, {}, ‘123’);      }    });    const appDoc = document.querySelector(‘#app’)    // 调用mount函数    app.mount(appDoc);    expect(document.body.innerHTML).toBe(‘<div id=”app”><div>123</div></div>’);  })})复制代码
流程图

    一开始需要createApp,那咋们就给一个,并且返回一个mount函数

functiоn createApp(rootComponent) {  const app = {    _component: rootComponent,    mount(container) {      const vnode = createVNode(rootComponent);      render(vnode, container);    }  };  return app;}复制代码

    mount内部需要创建vnode的方法,咋们也给一个,并且把跟组件作为参数传入

functiоn createVNode(type, props, children) { // 一开始咋们就是这么简单,vnode里面有一个type,props,children这几个关键的函数  const vnode = {    type,    props: props || {},    children: children || []  };  return vnode;}复制代码

    需要render函数,咋们也来创建一个,
    并且内容只调用了patch,咋把这两个一起创建

functiоn render(vnode, container) {  patch(vnode, container);}functiоn patch(vnode, container) {// patch需要判断vnode的type,如果是对象,则是处理组件,如果是字符串div,p等,则是处理元素  if (isObj(vnode.type)) {    processComponent(null, vnode, container);  } else if (String(vnode.type).length > 0) {    processElement(null, vnode, container);  }}复制代码

    咋们先处理组件吧,创建一个processComponent函数

// n1 是老节点,n2则是新节点,container是挂载的容器functiоn processComponent(n1, n2, container) {// 如果n1不存在,直接是挂载组件  if (!n1) {    mountComponent(n2, container);  }}复制代码

    创建mountComponent方法来挂载组件

functiоn mountComponent(vnode, container) {  // 创建组件实例  const instance = createComponentInstance(vnode);  // 处理组件,初始化setup,slot,props, render等在实例的挂载  setupComponent(instance);  // 执行render函数  setupRenderEffect(instance, vnode, container);}复制代码

    创建组件的实例createComponentInstance

// 是不是组件实例很简单,就只有一个vnode,props,functiоn createComponentInstance(vnode) {  const instance = {    vnode,    props: {},    type: vnode.type  };  return instance;}复制代码

    处理组件的状态, 这个函数里面会比较多内容

functiоn setupComponent(instance) {  const { props } = instance;  // 初始化props  initProps(instance, props);  // 处理组件的render函数  setupStatefulComponent(instance);}functiоn setupStatefulComponent(instance) {  const Component = instance.type;  const { setup } = Component;  // 是否存在setup  if (setup) {    const setupResult = setup();    // 处理setup的结果    handleSetupResult(instance, setupResult);  }  // 完成render在instance中  finishComponentSetup(instance);}functiоn handleSetupResult(instance, setupResult) {// 函数作为instance的render函数  if (isFunction(setupResult)) {    instance.render = setupResult;  } else if (isObj(setupResult)) {    instance.setupState = proxyRefs(setupResult);  }  finishComponentSetup(instance);}functiоn finishComponentSetup(instance) {  const Component = instance.type;  // 如果没有的话,直接使用Component的render  if (!instance.render) {    instance.render = Component.render;  }}复制代码

    创建setupRenderEffect,执行实例的render函数

functiоn setupRenderEffect(instance, vnode, container) {  const subtree = instance.render();  patch(subtree, container);}复制代码

    处理完组件,接下来该处理元素了 processElement

// 这个方法和processComponent一样functiоn processElement(n1, n2, container) {// 需要判断是更新还是挂载  if (n1) ; else {    mountElement(n2, container);  }}复制代码

    挂载元素 mountElement

functiоn mountElement(vnode, container) {// 创建根节点  const el = document.createElement(vnode.type);  const { props } = vnode;  // 挂载属性  for (let key in props) {    el.setAttribute(key, props[key]);  }  const children = vnode.children;  // 如果children是数组,继续patch  if (Array.isArray(children)) {    children.forEach((child) => {      patch(child, el);    });  } else if (String(children).length > 0) {    el.innerHTML = children;  }  // 把元素挂载到根节点  container.appendChild(el);}复制代码


恭喜,到这儿就完成本期的内容,重头看一下,
vue组件的挂载分为两种,处理组件和处理元素,最终回归到处理元素上面,最后实现节点的挂载,该内容是经过非常多删减,只是为了实现一个基本挂载,还有许多的边界都没有完善,后续继续加油‍‍‍

原创文章,作者:starterknow,如若转载,请注明出处:https://www.starterknow.com/126882.html

联系我们