VUE源码学习第六篇--new Vue都干了啥(挂载)

一、总述

  如果说前面的几部分都是准备工作,那么从挂载开始,就进入了正式的渲染工作,直到页面呈现出来。在开始分析代码前,我们可以思考下应该要做哪些工作。

1、将template中的各变量,表达式等替换成实际的值。比如:

 <div id="app">
   <ul>
    <li v-for="item in items">
      {{item.id}}
    </li>
  </ul>
<div>

..
var vm = new Vue({
    el:"#app",
    data:{
       items:[
        {id:1},
        {id:2},
        {id:3}
      ]
    }
})

替换后,形成实际的dom,并渲染出来

<div id="app">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
<div>

2、建立一种更新机制,当数据更新后,dom也重新渲染。比如items数组更新后,dome也随之更新。

实际上,vue也是围绕这两点展开的,下面是mount的过程的示意图。

(1)html字符串提取,无论是el还是template,最后都提取html的字符串。

(2)编译,将html得字符串编译成AST抽象数,再拼接成render表达式。

(3)形成真实的dom,render转化为vnode,最终生成实际的dom,并增加更新的监听。

下面我们就从源码分析,这部分涉及到的内容和知识点较多,有些内容我们会放到后面作为专门的章节进行介绍。

二、编译时的$mount

    Vue中$mount定义出现在两个文件中,分别是src/platform/web/entry-runtime-with-compiler.js、src/platform/web/runtime/index.js,前一个文件中,会将普通的template字符串转化成render语法,然后再调用后一个文件中的mount,完成dom的呈现。也就是在entry-runtime-with-compiler.js实现了编译的过程,如果我们采用的render语法编写的,那么只需要调用运行时的mount,这样可以节省编译的时间。但是实际开发中,vue是推荐用template模式的,毕竟可读性会更好。

我们看下entry-runtime-with-compiler.js的$mount

Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  //根据id获取dom元素
  el = el && query(el)

  /* istanbul ignore if */
  if (el === document.body || el === document.documentElement) {
    process.env.NODE_ENV !== 'production' && warn(
      `Do not mount Vue to <html> or <body> - mount to normal elements instead.`
    )
    return this
  }

  const options = this.$options
  // resolve template/el and convert to render function
  //1、根据template/el,获取html的字符串
  if (!options.render) {
    //获取template
    let template = options.template
    if (template) {
      if (typeof template === 'string') {
        if (template.charAt(0) === '#') {
          template = idToTemplate(template)
          /* istanbul ignore if */
          if (process.env.NODE_ENV !== 'production' && !template) {
            warn(
              `Template element not found or is empty: ${options.template}`,
              this
            )
          }
        }
      } else if (template.nodeType) {
        template = template.innerHTML
      } else {
        if (process.env.NODE_ENV !== 'production') {
          warn('invalid template option:' + template, this)
        }
        return this
      }
    } else if (el) {
      template = getOuterHTML(el)
    }
     //2、编译,生成render
    if (template) {
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile')
      }
      const { render, staticRenderFns } = compileToFunctions(template, {
        shouldDecodeNewlines,
        shouldDecodeNewlinesForHref,
        delimiters: options.delimiters,
        comments: options.comments
      }, this)
      options.render = render
      options.staticRenderFns = staticRenderFns

      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile end')
        measure(`vue ${this._name} compile`, 'compile', 'compile end')
      }
    }
  }
  //3、调用runtime的mount
  return mount.call(this, el, hydrating)
}

这个方法主要实现了

1、根据el或者template,获取到html的字符串,比如上面的例子,获取到的内容:

"<div id="app">
  <ul>
    <li v-for="item in items">
      {{item.id}}
    </li>
  </ul>
</div>"

2、将字符串转成render函数表达式,render的表达式我们前面也介绍过,熟悉react的同学对这个应该不陌生。这个过程涉及到编译,我们接下来有专门的章节去分析。最终转化后的render函数:

f() {
with(this){return _c('div',{attrs:{"id":"app"}},[_c('ul',_l((items),function(item){return _c('li',[_v("\n      "+_s(item.id)+"\n    ")])}))])}
}

3、调用runtime/index.js中的mount定义,继续后面的流程。

四、运行时的mount

将template(或者el指向的外部HTML)编译完成,转化成render函数后,运行时的moun负责真正的挂载过程。它将render表达式转化成vnode,最终创建真实的dom节点。

Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && inBrowser ? query(el) : undefined
  return mountComponent(this, el, hydrating)
}

   mount的入参有两个, 第一个是 el,它表示挂载的元素,可以是字符串,也可以是 DOM 对象,如果是字符串在浏览器环境下会调用 query 方法转换成 DOM 对象的。第二个参数是和服务端渲染相关,在浏览器环境下我们不需要传第二个参数。

返回了mountComponent方法。

export function mountComponent (
  vm: Component,
  el: ?Element,
  hydrating?: boolean
): Component {
  vm.$el = el
  if (!vm.$options.render) {
    vm.$options.render = createEmptyVNode
    if (process.env.NODE_ENV !== 'production') {
      /* 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
        )
      }
    }
  }
  //1、挂载前,执行beforMount
  callHook(vm, 'beforeMount')

  let updateComponent
  /* istanbul ignore if */
  if (process.env.NODE_ENV !== 'production' && 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 {
    //2、定义updateComponent,vm._render将render表达式转化为vnode,vm._update将vnode渲染成实际的dom节点
    updateComponent = () => {
      vm._update(vm._render(), hydrating)
    }
  }

  // we set this to vm._watcher inside the watcher's constructor
  // since the watcher's initial patch may call $forceUpdate (e.g. inside child
  // component's mounted hook), which relies on vm._watcher being already defined
  //3、首次渲染,并监听数据变化,并实现dom的更新
  new Watcher(vm, updateComponent, noop, {
    before () {
      if (vm._isMounted) {
        callHook(vm, 'beforeUpdate')
      }
    }
  }, true /* isRenderWatcher */)
  hydrating = false

  // manually mounted instance, call mounted on self
  // mounted is called for render-created child components in its inserted hook
  //4、挂载完成,回调mount函数
  if (vm.$vnode == null) {
    vm._isMounted = true
    callHook(vm, 'mounted')
  }
  return vm
}

这里展示了完整的挂载过程。

1、执行beforeMount回调方法。此时el已经赋值给vm.$el。以VUE源码学习第三篇--new Vue都干了啥(概述)的样例为例,el已经有值了。

 beforeMount(){
    console.log("beforeMount");
     console.log("this el:"+this.$el);//[object HTMLDivElement]
     console.log("this data:"+this.$data);//[object Object]
     console.log("this msg:"+this.msg);//tttt
   }

2、定义updateComponent方法,vm._render,实现将render表达式转化成vnode,vm._update将vnode渲染成实际的dom。

3、构建watcher实例,它有两个作用,

(1)执行updateComponent方法,实现dom的渲染,并完成表达式对属性变量的依赖收集。

  (2)一旦包含的表达式中的属性变量有变化,将重新执行update。

关于watcher部分,将在后续的响应式原理中分析,当前阶段仅做了解。

4、判断是否是根节点,执行挂载完成的回调方法。

接下来我们重点讲下render和update过程。

五、vm._render

该方法是将render表达式转化为vnode,首先我们看看什么是vnode,vnode位于core/vdom/vnode.js中,定义如下:

export default class VNode {
  tag: string | void;
  data: VNodeData | void;
  children: ?Array<VNode>;
  text: string | void;
  elm: Node | void;
  ns: string | void;
  context: Component | void; // rendered in this component's scope
  key: string | number | void;
  componentOptions: VNodeComponentOptions | void;
  componentInstance: Component | void; // component instance
  parent: VNode | void; // component placeholder node

  // strictly internal
  raw: boolean; // contains raw HTML? (server only)
  isStatic: boolean; // hoisted static node
  isRootInsert: boolean; // necessary for enter transition check
  isComment: boolean; // empty comment placeholder?
  isCloned: boolean; // is a cloned node?
  isOnce: boolean; // is a v-once node?
  asyncFactory: Function | void; // async component factory function
  asyncMeta: Object | void;
  isAsyncPlaceholder: boolean;
  ssrContext: Object | void;
  fnContext: Component | void; // real context vm for functional nodes
  fnOptions: ?ComponentOptions; // for SSR caching
  fnScopeId: ?string; // functional scope id support

  constructor (
    tag?: string,
    data?: VNodeData,
    children?: ?Array<VNode>,
    text?: string,
    elm?: Node,
    context?: Component,
    componentOptions?: VNodeComponentOptions,
    asyncFactory?: Function
  ) {
    /*当前节点的标签名*/
    this.tag = tag
    /*当前节点对应的对象,包含了具体的一些数据信息,是一个VNodeData类型,可以参考VNodeData类型中的数据信息*/
    this.data = data
    /*当前节点的子节点,是一个数组*/
    this.children = children
    /*当前节点的文本*/
    this.text = text
     /*当前虚拟节点对应的真实dom节点*/
    this.elm = elm
    /*当前节点的名字空间*/
    this.ns = undefined
    /*编译作用域*/
    this.context = context
    /*函数化组件作用域*/
    this.fnContext = undefined
    this.fnOptions = undefined
    this.fnScopeId = undefined
    /*节点的key属性,被当作节点的标志,用以优化*/
    this.key = data && data.key
    /*组件的option选项*/
    this.componentOptions = componentOptions
    /*当前节点对应的组件的实例*/
    this.componentInstance = undefined
     /*当前节点的父节点*/
    this.parent = undefined
    /*简而言之就是是否为原生HTML或只是普通文本,innerHTML的时候为true,textContent的时候为false*/
    this.raw = false
    /*静态节点标志*/
    this.isStatic = false
    /*是否作为跟节点插入*/
    this.isRootInsert = true
    /*是否为注释节点*/
    this.isComment = false
    /*是否为克隆节点*/
    this.isCloned = false
    /*是否有v-once指令*/
    this.isOnce = false
    /*异步组件的工厂方法*/
    this.asyncFactory = asyncFactory
    /*异步源*/
    this.asyncMeta = undefined
     /*是否异步的预赋值*/
    this.isAsyncPlaceholder = false
  }

  // DEPRECATED: alias for componentInstance for backwards compat.
  /* istanbul ignore next */
  get child (): Component | void {
    return this.componentInstance
  }
}

vnode就是一系列dom属性的集合,可以认为是简化了的dom。

vm._render位于src/core/instance/render.js,

  Vue.prototype._render = function (): VNode {
   ...
    try {
      //核心代码,生成vnode
      vnode = render.call(vm._renderProxy, vm.$createElement)
    } catch (e) {
      ...
    }
    // set parent
    vnode.parent = _parentVnode
    return vnode
  }

我们直接看核心代码,vm._renderProxy是执行的上下文,我们前面讲过,在生产环境中就是vm,如果对call函数不了解的,翻译成vm.render(vm.$createElement),可能更加易于理解。

参见本例中的render函数,调用的是vm._c创建各级的vnode,那么这个函数在哪定义的呢,前一章节讲到的initRender方法中

//定义._c方法,对template进行render处理的方法
  vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false)

createElement位于src/core/vdom/create-element.js中

export function createElement (
  context: Component,
  tag: any,
  data: any,
  children: any,
  normalizationType: any,
  alwaysNormalize: boolean
): VNode | Array<VNode> {
   //处理data的入参,当没有data属性的情况下,这个参数表示的是children
  if (Array.isArray(data) || isPrimitive(data)) {
    normalizationType = children
    children = data
    data = undefined
  }
  if (isTrue(alwaysNormalize)) {
    normalizationType = ALWAYS_NORMALIZE
  }
  return _createElement(context, tag, data, children, normalizationType)
}

我们看到createElement是对_createElement的封装,处理不同的入参写法。继续看_createElement这个方法的代码

export function _createElement (
  context: Component,
  tag?: string | Class<Component> | Function | Object,
  data?: VNodeData,
  children?: any,
  normalizationType?: number
): VNode | Array<VNode> {
  if (isDef(data) && isDef((data: any).__ob__)) {
    process.env.NODE_ENV !== 'production' && warn(
      `Avoid using observed data object as vnode data: ${JSON.stringify(data)}\n` +
      'Always create fresh vnode data objects in each render!',
      context
    )
    return createEmptyVNode()
  }
  // object syntax in v-bind
  if (isDef(data) && isDef(data.is)) {
    tag = data.is
  }
  if (!tag) {
    // in case of component :is set to falsy value
    return createEmptyVNode()
  }
  // warn against non-primitive key
  if (process.env.NODE_ENV !== 'production' &&
    isDef(data) && isDef(data.key) && !isPrimitive(data.key)
  ) {
    if (!__WEEX__ || !('@binding' in data.key)) {
      warn(
        'Avoid using non-primitive value as key, ' +
        'use string/number value instead.',
        context
      )
    }
  }
  // support single function children as default scoped slot
  if (Array.isArray(children) &&
    typeof children[0] === 'function'
  ) {
    data = data || {}
    data.scopedSlots = { default: children[0] }
    children.length = 0
  }

  //1、规整childern子节点
  if (normalizationType === ALWAYS_NORMALIZE) {
    children = normalizeChildren(children)
  } else if (normalizationType === SIMPLE_NORMALIZE) {
    children = simpleNormalizeChildren(children)
  }
  let vnode, ns
  //2、创建vnode
  if (typeof tag === 'string') {
    let Ctor
    ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag)
    if (config.isReservedTag(tag)) {
      // platform built-in elements
      vnode = new VNode(
        config.parsePlatformTagName(tag), data, children,
        undefined, undefined, context
      )
    } else if (isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {
      // component
      vnode = createComponent(Ctor, data, context, children, tag)
    } else {
      // unknown or unlisted namespaced elements
      // check at runtime because it may get assigned a namespace when its
      // parent normalizes children
      vnode = new VNode(
        tag, data, children,
        undefined, undefined, context
      )
    }
  } else {
    // direct component options / constructor
    vnode = createComponent(tag, data, context, children)
  }
  if (Array.isArray(vnode)) {
    return vnode
  } else if (isDef(vnode)) {
    if (isDef(ns)) applyNS(vnode, ns)
    if (isDef(data)) registerDeepBindings(data)
    return vnode
  } else {
    return createEmptyVNode()
  }
}

    有5个入参,context表示上下文,即当前的组件对象,tag表示node的标签,data表示是组件的data数据,VNode类型,children表示当前的子节点,normalizationType表示子节点的规范类型,对于手写的render方法需要进行规整。

  该方法主要的包含两个功能,对children进行规整,以及创建vnode。

1、children规整

// 1. When the children contains components - because a functional component
// may return an Array instead of a single root. In this case, just a simple
// normalization is needed - if any child is an Array, we flatten the whole
// thing with Array.prototype.concat. It is guaranteed to be only 1-level deep
// because functional components already normalize their own children.
export function simpleNormalizeChildren (children: any) {
  for (let i = 0; i < children.length; i++) {
    if (Array.isArray(children[i])) {
      return Array.prototype.concat.apply([], children)
    }
  }
  return children
}

// 2. When the children contains constructs that always generated nested Arrays,
// e.g. <template>, <slot>, v-for, or when the children is provided by user
// with hand-written render functions / JSX. In such cases a full normalization
// is needed to cater to all possible types of children values.
export function normalizeChildren (children: any): ?Array<VNode> {
  return isPrimitive(children)
    ? [createTextVNode(children)]
    : Array.isArray(children)
      ? normalizeArrayChildren(children)
      : undefined
}

simpleNormalizeChildren是指对函数式组件的处理,函数式组件返回的是一个数组而不是一个根节点,需要通过Array.prototype.concat将数组平整化,让它只有一层的深度。

normalizeChildren处理手写的render函数或者JSX,当children是基础的类型时,通过createTextVNode创建Textvnode节点;当编译v-for,slot时会产生嵌套数组时,调用normalizeArrayChildren处理。

经过children的规整,children变成一个类型为VNode的Array。

2、创建vnode

首先判断tag是否为String类型,接着判断是否为内置标签(html或者svg标签,比如div,body等等),如果是,则创建一个普通的VNode,初始化tag,data,children等变量。

如果是已注册的组件,则调用createComponent创建VNode,否则创建一个未知标签的VNode。如果不是个String类型,调用createComponent创建组件类型的VNode,关于组件的创建过程我们后续再讲。

总之,通过createElement后,就创建了vnode的tree,这个就是虚拟的DOM。

六、vm._update

vm._update会把vnode渲染成真实的dom节点,它调用的时机有两个地方,第一个是首次渲染,第二个是数据更新。本章节我们仅关注第一种情况。数据的更新我们放到后面专门章节分析。vm._update定义在src/core/instance/lifecycle.js中。

 Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
    ...
    if (!prevVnode) {
      // initial render
      vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
    } else {
      // updates
      vm.$el = vm.__patch__(prevVnode, vnode)
    }
    ...
  }

我们看下核心代码,调用vm.__patch__进行首次渲染。web平台定义在src/platforms/web/runtime/index.js中

// install platform patch function
Vue.prototype.__patch__ = inBrowser ? patch : noop

如果是浏览器环境,则为src/platforms/web/runtime/patch.js(服务端渲染则无需,为空函数)。

export const patch: Function = createPatchFunction({ nodeOps, modules })

createPatchFunction返回patch函数,定义在src/core/vdom/patch.js中。

export function createPatchFunction (backend) {
...
  return function patch (oldVnode, vnode, hydrating, removeOnly) {
    if (isUndef(vnode)) {
      if (isDef(oldVnode)) invokeDestroyHook(oldVnode)
      return
    }

    let isInitialPatch = false
    const insertedVnodeQueue = []

    if (isUndef(oldVnode)) {
      // empty mount (likely as component), create new root element
      isInitialPatch = true
      createElm(vnode, insertedVnodeQueue)
    } else {
      //是否是实际的元素
      const isRealElement = isDef(oldVnode.nodeType)
      if (!isRealElement && sameVnode(oldVnode, vnode)) {
        // patch existing root node
        patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly)
      } else {
        if (isRealElement) {
          // mounting to a real element
          // check if this is server-rendered content and if we can perform
          // a successful hydration.
          if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) {
            oldVnode.removeAttribute(SSR_ATTR)
            hydrating = true
          }
          if (isTrue(hydrating)) {
            if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
              invokeInsertHook(vnode, insertedVnodeQueue, true)
              return oldVnode
            } else if (process.env.NODE_ENV !== 'production') {
              warn(
                'The client-side rendered virtual DOM tree is not matching ' +
                'server-rendered content. This is likely caused by incorrect ' +
                'HTML markup, for example nesting block-level elements inside ' +
                '<p>, or missing <tbody>. Bailing hydration and performing ' +
                'full client-side render.'
              )
            }
          }
          // either not server-rendered, or hydration failed.
          // create an empty node and replace it
          //转成vnode
          oldVnode = emptyNodeAt(oldVnode)
        }

        // replacing existing element
        const oldElm = oldVnode.elm
        const parentElm = nodeOps.parentNode(oldElm)

        // create new node
        //核心方法,根据vnode渲染成实际的dom
        createElm(
          vnode,
          insertedVnodeQueue,
          // extremely rare edge case: do not insert if old element is in a
          // leaving transition. Only happens when combining transition +
          // keep-alive + HOCs. (#4590)
          oldElm._leaveCb ? null : parentElm,
          nodeOps.nextSibling(oldElm)
        )

        // update parent placeholder node element, recursively
        if (isDef(vnode.parent)) {
          let ancestor = vnode.parent
          const patchable = isPatchable(vnode)
          while (ancestor) {
            for (let i = 0; i < cbs.destroy.length; ++i) {
              cbs.destroy[i](ancestor)
            }
            ancestor.elm = vnode.elm
            if (patchable) {
              for (let i = 0; i < cbs.create.length; ++i) {
                cbs.create[i](emptyNode, ancestor)
              }
              // #6513
              // invoke insert hooks that may have been merged by create hooks.
              // e.g. for directives that uses the "inserted" hook.
              const insert = ancestor.data.hook.insert
              if (insert.merged) {
                // start at index 1 to avoid re-invoking component mounted hook
                for (let i = 1; i < insert.fns.length; i++) {
                  insert.fns[i]()
                }
              }
            } else {
              registerRef(ancestor)
            }
            ancestor = ancestor.parent
          }
        }

        // destroy old node
        if (isDef(parentElm)) {
          removeVnodes(parentElm, [oldVnode], 0, 0)
        } else if (isDef(oldVnode.tag)) {
          invokeDestroyHook(oldVnode)
        }
      }
    }

    invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch)
    return vnode.elm
  }
...
}

createPatchFunction内部定义了一系列方法,最后返回了patch方法,它有四个参数,实际在vm.__patch__(vm.$el, vnode, hydrating, false )传入。我们还以开篇的样例为例,vm.$el是id为app的dom,vnode是render后的虚拟对象,hydrating表示是否是服务端渲染,最后一个参数removeOnly 是给 transition-group 用的。

 oldVnode是id为app的实际的dom,所以isRealElement为ture,emptyNodeAt将oldVnode转成Vnode对象。接下来调用createElm创建真实的dom,我们重点看下这个方法。

 function createElm (
    vnode,
    insertedVnodeQueue,
    parentElm,
    refElm,
    nested,
    ownerArray,
    index
  ) {
    if (isDef(vnode.elm) && isDef(ownerArray)) {
      // This vnode was used in a previous render!
      // now it's used as a new node, overwriting its elm would cause
      // potential patch errors down the road when it's used as an insertion
      // reference node. Instead, we clone the node on-demand before creating
      // associated DOM element for it.
      vnode = ownerArray[index] = cloneVNode(vnode)
    }

    vnode.isRootInsert = !nested // for transition enter check
    if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) {
      return
    }

    const data = vnode.data
    const children = vnode.children
    const tag = vnode.tag
    //1、合法性校验
    if (isDef(tag)) {
      if (process.env.NODE_ENV !== 'production') {
        if (data && data.pre) {
          creatingElmInVPre++
        }
        if (isUnknownElement(vnode, creatingElmInVPre)) {
          warn(
            'Unknown custom element: <' + tag + '> - did you ' +
            'register the component correctly? For recursive components, ' +
            'make sure to provide the "name" option.',
            vnode.context
          )
        }
      }
      //2、创建该vnode的dom元素
      vnode.elm = vnode.ns
        ? nodeOps.createElementNS(vnode.ns, tag)
        : nodeOps.createElement(tag, vnode)
      setScope(vnode)

      /* istanbul ignore if */
      if (__WEEX__) {
        // in Weex, the default insertion order is parent-first.
        // List items can be optimized to use children-first insertion
        // with append="tree".
        const appendAsTree = isDef(data) && isTrue(data.appendAsTree)
        if (!appendAsTree) {
          if (isDef(data)) {
            invokeCreateHooks(vnode, insertedVnodeQueue)
          }
          insert(parentElm, vnode.elm, refElm)
        }
        createChildren(vnode, children, insertedVnodeQueue)
        if (appendAsTree) {
          if (isDef(data)) {
            invokeCreateHooks(vnode, insertedVnodeQueue)
          }
          insert(parentElm, vnode.elm, refElm)
        }
      } else {
        //3、创建子节点
        createChildren(vnode, children, insertedVnodeQueue)
        //4、执行所有的create钩子
        if (isDef(data)) {
          invokeCreateHooks(vnode, insertedVnodeQueue)
        }
        //5、插入节点
        insert(parentElm, vnode.elm, refElm)
      }

      if (process.env.NODE_ENV !== 'production' && data && data.pre) {
        creatingElmInVPre--
      }
    } else if (isTrue(vnode.isComment)) {
      vnode.elm = nodeOps.createComment(vnode.text)
      insert(parentElm, vnode.elm, refElm)
    } else {
      vnode.elm = nodeOps.createTextNode(vnode.text)
      insert(parentElm, vnode.elm, refElm)
    }
  }

首先对tag进行合法性校验,通过nodeOps.createElement实现元素的创建。我们来看下这个方法,位于src/plateforms/web/runtime/node-ops.js

export function createElement (tagName: string, vnode: VNode): Element {
  //核心方法
  const elm = document.createElement(tagName)
  if (tagName !== 'select') {
    return elm
  }
  // false or null will remove the attribute but undefined will not
  if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) {
    elm.setAttribute('multiple', 'multiple')
  }
  return elm
}

最终是调用原生的方法document.createElement,setAttribute实现了dom节点的创建。

接下来,调用createChildren方法创建子节点元素。

function createChildren (vnode, children, insertedVnodeQueue) {
    //如果有子节点,则调用creatElm递归创建
    if (Array.isArray(children)) {
      if (process.env.NODE_ENV !== 'production') {
        checkDuplicateKeys(children)
      }
      for (let i = 0; i < children.length; ++i) {
        createElm(children[i], insertedVnodeQueue, vnode.elm, null, true, children, i)
      }
    } else if (isPrimitive(vnode.text)) {//对于叶节点,直接添加text
      nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(String(vnode.text)))
    }
  }

如果有子节点,则递归调用creatElm创建,对于叶节点,则直接添加到元素。

子节点的元素创建完成后,调用 invokeCreateHooks 方法执行所有的 create 的钩子并把 vnode push 到 insertedVnodeQueue 中。

最后调用insert将dom插入到父元素。由于是递归调用,所以子元素要先于父元素插入。insert过程中调用的是原生的appendChild将元素插入。

对于我们的例子,创建和插入的顺序li->ul->div,最后将完成的DOM插入到body中。

至此,首次渲染完成,我们看到最终都是采用原生的方法,如createElement,setAttribute,appendChild等实现节点的创建。

七、总结

通过各种init,以及mount,我们的new Vue也结束,也将最初的数据和模板最终渲染成了实际的DOM。下面是前人总结的一张流程总览图,我觉得非常好,简单明了。

在整个分析过程中,我们尽量忽略了很多细节,让大家对主线有个清楚的认识。那么在接下来的章节中,我们就需要对这些知识进行学习。

发布了33 篇原创文章 · 获赞 95 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/tcy83/article/details/86566589