自学vue3源码 | 初看渲染流程(1)

216 阅读1分钟
const Counter = {
  data() {
    return {
      counter: 0
    }
  }
}

Vue.createApp(Counter).mount('#counter')

实例创建完成之后就要执行mount方法,通过上一篇文章我们已经知道mount是怎么生成。

//packages\runtime-dom\src\index.ts
export const createApp = ((...args) => {
  const app = ensureRenderer().createApp(...args)
  //缓存mount方法
  const { mount } = app
  // 重写mount方法
  app.mount = (containerOrSelector: Element | ShadowRoot | string): any => {
    // 标准化容器 
    const container = normalizeContainer(containerOrSelector);
    const component = app._component
    if (!isFunction(component) && !component.render && !component.template) {
      component.template = container.innerHTML
    }
    // 挂载前清空容器内容
    container.innerHTML = "";
    const proxy = mount(container, false, container instanceof SVGElement)
    return proxy
  }

  return app
})

先通过normalizeContainer获取到DOM对象作为渲染的容器, 如果组件对象没有定义 render 函数和 template 模板,则取容器的 innerHTML 作为组件模板内容,挂载前清空容器内容,最后调用app.mount。