vue2.7.16源码 - web runtime

46 阅读1分钟

src/platforms/web/runtime/index.ts - dom核心

  • dom核心,通过在core/index导出的Vue构造函数的基础上增强属性,实现$mount,开启和devtools的通信

    • import Vue from 'core/index'
      import config from 'core/config'
      import { extend, noop } from 'shared/util'
      import { mountComponent } from 'core/instance/lifecycle'
      import { devtools, inBrowser } from 'core/util/index'
      
      import {
        query,
        mustUseProp,
        isReservedTag,
        isReservedAttr,
        getTagNamespace,
        isUnknownElement
      } from 'web/util/index'
      
      import { patch } from './patch'
      import platformDirectives from './directives/index'
      import platformComponents from './components/index'
      import type { Component } from 'types/component'
      
      // 插入一些web端的工具函数
      Vue.config.mustUseProp = mustUseProp
      Vue.config.isReservedTag = isReservedTag
      Vue.config.isReservedAttr = isReservedAttr
      Vue.config.getTagNamespace = getTagNamespace
      Vue.config.isUnknownElement = isUnknownElement
      
      // 预置model 和show 两个自定义指令
      extend(Vue.options.directives, platformDirectives)
      
      //预置 Transition TransitionGroup 两个全局组件
      extend(Vue.options.components, platformComponents)
      
      // 判断环境保留对应的dom创建函数
      Vue.prototype.__patch__ = inBrowser ? patch : noop
      
      // 组件挂载$mount函数
      Vue.prototype.$mount = function (
        el?: string | Element,
        hydrating?: boolean
      ): Component {
        el = el && inBrowser ? query(el) : undefined
        return mountComponent(this, el, hydrating)
      }
      
      // 联动devtools
      if (inBrowser) {
        setTimeout(() => {
          if (config.devtools) {
            if (devtools) {
              devtools.emit('init', Vue)
            } else if (__DEV__ && process.env.NODE_ENV !== 'test') {
              // @ts-expect-error
              console[console.info ? 'info' : 'log'](
                'Download the Vue Devtools extension for a better development experience:\n' +
                  'https://github.com/vuejs/vue-devtools'
              )
            }
          }
          if (
            __DEV__ &&
            process.env.NODE_ENV !== 'test' &&
            config.productionTip !== false &&
            typeof console !== 'undefined'
          ) {
            // @ts-expect-error
            console[console.info ? 'info' : 'log'](
              `You are running Vue in development mode.\n` +
                `Make sure to turn on production mode when deploying for production.\n` +
                `See more tips at https://vuejs.org/guide/deployment.html`
            )
          }
        }, 0)
      }
      
      export default Vue
      
  • src/core/instance/lifecycle.ts - mountComponent实现, 挂载真实dom

    • export function mountComponent(
        vm: Component,
        el: Element | null | undefined,
        hydrating?: boolean
      ): Component {
        vm.$el = el
        // 没有render方法
        if (!vm.$options.render) {
          // 创建空的vnode
          vm.$options.render = createEmptyVNode
          if (__DEV__) {
            /* istanbul ignore if */
            if (
              (vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
              vm.$options.el ||
              el
            ) {
              warn(
                'You are using the runtime-only build of Vue where the template ' +
                  'compiler is not available. Either pre-compile the templates into ' +
                  'render functions, or use the compiler-included build.',
                vm
              )
            } else {
              warn(
                'Failed to mount component: template or render function not defined.',
                vm
              )
            }
          }
        }
        // 触发beforeMount生命周期
        callHook(vm, 'beforeMount')
      
        let updateComponent
        /* istanbul ignore if */
        if (__DEV__ && config.performance && mark) {
          updateComponent = () => {
            const name = vm._name
            const id = vm._uid
            const startTag = `vue-perf-start:${id}`
            const endTag = `vue-perf-end:${id}`
      
            mark(startTag)
            const vnode = vm._render()
            mark(endTag)
            measure(`vue ${name} render`, startTag, endTag)
      
            mark(startTag)
            vm._update(vnode, hydrating)
            mark(endTag)
            measure(`vue ${name} patch`, startTag, endTag)
          }
        } else {
        // 更新dom节点
          updateComponent = () => {
            vm._update(vm._render(), hydrating)
          }
        }
      
      // Watcher触发一次更新 触发 beforeUpdate 事件
        const watcherOptions: WatcherOptions = {
          before() {
            if (vm._isMounted && !vm._isDestroyed) {
              callHook(vm, 'beforeUpdate')
            }
          }
        }
      
        if (__DEV__) {
          watcherOptions.onTrack = e => callHook(vm, 'renderTracked', [e])
          watcherOptions.onTrigger = e => callHook(vm, 'renderTriggered', [e])
        }
      
        // 创建新的Watcher
        new Watcher(
          vm,
          updateComponent,
          noop,
          watcherOptions,
          true /* isRenderWatcher */
        )
        hydrating = false
      
        // 调用之前创建的Watcher
        const preWatchers = vm._preWatchers
        if (preWatchers) {
          for (let i = 0; i < preWatchers.length; i++) {
            preWatchers[i].run()
          }
        }
      
       // 节点更新完成 触发 mounted 生命周期
        if (vm.$vnode == null) {
          vm._isMounted = true
          callHook(vm, 'mounted')
        }
        return vm
      }
      
  • src/core/vdom/vnode.ts - createEmptyVNode实现

src/platforms/web/runtime-with-compiler.ts

  • 原型上$mount实现,包含模板编译执行,然后执行mountComponent,编译成真实dom,触发生命周期
  • mountComponent 会启动 renderWatcher 开始构建渲染
import config from 'core/config'
import { warn, cached } from 'core/util/index'
import { mark, measure } from 'core/util/perf'

import Vue from './runtime/index'
import { query } from './util/index'
import { compileToFunctions } from './compiler/index'
import {
  shouldDecodeNewlines,
  shouldDecodeNewlinesForHref
} from './util/compat'
import type { Component } from 'types/component'
import type { GlobalAPI } from 'types/global-api'

const idToTemplate = cached(id => {
  const el = query(id)
  return el && el.innerHTML
})

const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  // 查找元素 没有找到创建一个 div
  el = el && query(el)

  /* istanbul ignore if */
  // 不能挂载到body
  if (el === document.body || el === document.documentElement) {
    __DEV__ &&
      warn(
        `Do not mount Vue to <html> or <body> - mount to normal elements instead.`
      )
    return this
  }

  const options = this.$options
  // 没有render函数 需要判断template
  if (!options.render) {
    let template = options.template
    if (template) {
      if (typeof template === 'string') {
      // 字符串话找对应节点 获取对应的html
        if (template.charAt(0) === '#') {
          template = idToTemplate(template)
          /* istanbul ignore if */
          if (__DEV__ && !template) {
            warn(
              `Template element not found or is empty: ${options.template}`,
              this
            )
          }
        }
      } else if (template.nodeType) {
      // 如果带有nodetype 直接获取innerHTML属性
        template = template.innerHTML
      } else {
        if (__DEV__) {
          warn('invalid template option:' + template, this)
        }
        return this
      }
    } else if (el) {
      // 目标元素获取html
      template = getOuterHTML(el)
    }
    if (template) {
      /* istanbul ignore if */
      if (__DEV__ && config.performance && mark) {
        mark('compile')
      }
     // 模板转成render函数 获取静态节点编译函数
      const { render, staticRenderFns } = compileToFunctions(
        template,
        {
          outputSourceRange: __DEV__,
          shouldDecodeNewlines,
          shouldDecodeNewlinesForHref,
          delimiters: options.delimiters,
          comments: options.comments
        },
        this
      )
      // 保存render函数
      options.render = render
      // 保存静态节点渲染函数
      options.staticRenderFns = staticRenderFns

      /* istanbul ignore if */
      if (__DEV__ && config.performance && mark) {
        mark('compile end')
        measure(`vue ${this._name} compile`, 'compile', 'compile end')
      }
    }
  }
  // 触发mountComponent
  return mount.call(this, el, hydrating)
}

/**
 * Get outerHTML of elements, taking care
 * of SVG elements in IE as well.
 */
function getOuterHTML(el: Element): string {
  if (el.outerHTML) {
    return el.outerHTML
  } else {
    const container = document.createElement('div')
    container.appendChild(el.cloneNode(true))
    return container.innerHTML
  }
}

// 保存模板编译函数
Vue.compile = compileToFunctions

export default Vue as GlobalAPI