likes
comments
collection
share

vue3 createApp 源码阅读

作者站长头像
站长
· 阅读数 42

createApp 主要做了那些事情?

  • 首先它是在 /packages/runtime-dom/src/index.ts 中定义的
  • 用根组件创建一个应用实例
  • 重写了挂载这个根组件方法 mount
// /packages/runtime-dom/src/index.ts
export const createApp = ((...args) => { // 我们传过来的一般只有一个根组件配置项
  const app = ensureRenderer().createApp(...args) // 主要实现在这里

  if (__DEV__) { // 
    injectNativeTagCheck(app)
    injectCompilerOptionsCheck(app)
  }

  const { mount } = app
  app.mount = (containerOrSelector: Element | ShadowRoot | string): any => {
    const container = normalizeContainer(containerOrSelector)
    if (!container) return

    const component = app._component
    if (!isFunction(component) && !component.render && !component.template) {
      // __UNSAFE__
      // Reason: potential execution of JS expressions in in-DOM template.
      // The user must make sure the in-DOM template is trusted. If it's
      // rendered by the server, the template should not contain any user data.
      component.template = container.innerHTML
      // 2.x compat check
      if (__COMPAT__ && __DEV__) {
        for (let i = 0; i < container.attributes.length; i++) {
          const attr = container.attributes[i]
          if (attr.name !== 'v-cloak' && /^(v-|:|@)/.test(attr.name)) {
            compatUtils.warnDeprecation(
              DeprecationTypes.GLOBAL_MOUNT_CONTAINER,
              null,
            )
            break
          }
        }
      }
    }

    // clear content before mounting
    container.innerHTML = ''
    const proxy = mount(container, false, resolveRootNamespace(container))
    if (container instanceof Element) {
      container.removeAttribute('v-cloak')
      container.setAttribute('data-v-app', '')
    }
    return proxy
  }

  return app
}) as CreateAppFunction<Element>

创建实例的实现是在哪里?

  • 在渲染器 render
  • render 的真正创建方法 baseCreateRenderer 是在 /packages/runtime-core/src/rendere r.ts 中实现的,它会返回创建实例的具体方法 createApp
  • createApp 又是由/packages/runtime-core/src/apiCrea teApp.tscreateAppAPI方法创建的
  • createAppAPI 会返回一个 createApp 方法,它是创建应用实例的具体实现

createAppAPI 返回的 createApp 主要做了哪些事呢?

  • 浅拷贝一份 rootComponent
  • 校验 rootProps, 如果不是 null 必须是一个对象
  • 创建根组件的上下文对象
  • 创建一个 app 实例字面两对象

vue3 createApp 源码阅读

app._component 和 app._instance 的区别

  • _component 是根组件的配置项
  • _instance 组件内部实例

总结

  • 创建并返回一个 app 实例
  • app 实例里有很多实例属性和方法
  • 实力属性和方法有这些

vue3 createApp 源码阅读

转载自:https://juejin.cn/post/7372036291922575395
评论
请登录