Vue源碼分析—數(shù)據(jù)驅(qū)動(二)

Virtual DOM

Virtual DOM這個概念相信大部分人都不會陌生,它產(chǎn)生的前提是瀏覽器中的DOM是很“昂貴"的,為了更直觀的感受,我們可以簡單的把一個簡單的div元素的屬性都打印出來,如圖所示:

可以看到,真正的DOM元素是非常龐大的,因為瀏覽器的標(biāo)準(zhǔn)就把DOM設(shè)計的非常復(fù)雜。當(dāng)我們頻繁的去做DOM更新,會產(chǎn)生一定的性能問題。
Virtual DOM就是用一個原生的JS對象去描述一個DOM節(jié)點,所以它比創(chuàng)建一個DOM的代價要小很多。在Vue.js中,Virtual DOM是用VNode這么一個Class去描述,它是定義在src/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
    this.data = data
    this.children = children
    this.text = text
    this.elm = elm
    this.ns = undefined
    this.context = context
    this.fnContext = undefined
    this.fnOptions = undefined
    this.fnScopeId = undefined
    this.key = data && data.key
    this.componentOptions = componentOptions
    this.componentInstance = undefined
    this.parent = undefined
    this.raw = false
    this.isStatic = false
    this.isRootInsert = true
    this.isComment = false
    this.isCloned = false
    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
  }
}

實際上Vue.js中Virtual DOM是借鑒了一個開源庫snabbdom 的實現(xiàn),然后加入了一些Vue.js特色的東西。這個庫更加簡單和純粹。
其實VNode是對真實DOM的一種抽象描述,它的核心定義無非就幾個關(guān)鍵屬性,標(biāo)簽名、數(shù)據(jù)、子節(jié)點、鍵值等,其它屬性都是都是用來擴展VNode的靈活性以及實現(xiàn)一些特殊feature的。由于VNode只是用來映射到真實DOM的渲染,不需要包含操作DOM的方法,因此它是非常輕量和簡單的。
Virtual DOM除了它的數(shù)據(jù)結(jié)構(gòu)的定義,映射到真實的DOM實際上要經(jīng)歷VNodecreate、diff、patch等過程。那么在Vue.js中,VNodecreate是通過之前提到的createElement方法創(chuàng)建的。

createElement

Vue.js利用createElement方法創(chuàng)建VNode,它定義在src/core/vdom/create-elemenet.js中:

// wrapper function for providing a more flexible interface
// without getting yelled at by flow
export function createElement (
  context: Component,
  tag: any,
  data: any,
  children: any,
  normalizationType: any,
  alwaysNormalize: boolean
): VNode | Array<VNode> {
  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方法的封裝,它允許傳入的參數(shù)更加靈活,在處理這些參數(shù)后,調(diào)用真正創(chuàng)建VNode的函數(shù)_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
  }
  if (normalizationType === ALWAYS_NORMALIZE) {
    children = normalizeChildren(children)
  } else if (normalizationType === SIMPLE_NORMALIZE) {
    children = simpleNormalizeChildren(children)
  }
  let vnode, ns
  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()
  }
}

_createElement方法有5個參數(shù),context表示VNode的上下文環(huán)境,它是Component類型;tag 表示標(biāo)簽,它可以是一個字符串,也可以是一個Componentdata表示VNode的數(shù)據(jù),它是一個VNodeData類型,可以在flow/vnode.js中找到它的定義,這里先不展開說;children表示當(dāng)前VNode的子節(jié)點,它是任意類型的,它接下來需要被規(guī)范為標(biāo)準(zhǔn)的VNode數(shù)組;normalizationType表示子節(jié)點規(guī)范的類型,類型不同規(guī)范的方法也就不一樣,它主要是參考 render 函數(shù)是編譯生成的還是用戶手寫的。
createElement函數(shù)的流程略微有點多,我們接下來主要分析2個重點的流程——children的規(guī)范化以及VNode的創(chuàng)建。

children的規(guī)范化

由于Virtual DOM實際上是一個樹狀結(jié)構(gòu),每一個VNode可能會有若干個子節(jié)點,這些子節(jié)點應(yīng)該也是VNode的類型。_createElement接收的第 4個參數(shù)children是任意類型的,因此我們需要把它們規(guī)范成VNode類型。
這里根據(jù)normalizationType的不同,調(diào)用了normalizeChildren(children)simpleNormalizeChildren(children)方法,它們的定義都在src/core/vdom/helpers/normalzie-children.js中:

// The template compiler attempts to minimize the need for normalization by
// statically analyzing the template at compile time.
//
// For plain HTML markup, normalization can be completely skipped because the
// generated render function is guaranteed to return Array<VNode>. There are
// two cases where extra normalization is needed:

// 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方法調(diào)用場景是render函數(shù)是編譯生成的。理論上編譯生成的children都已經(jīng)是VNode類型的,但這里有一個例外,就是functional component函數(shù)式組件返回的是一個數(shù)組而不是一個根節(jié)點,所以會通過Array.prototype.concat方法把整個children數(shù)組打平,讓它的深度只有一層。

normalizeChildren方法的調(diào)用場景有2種,一個場景是render函數(shù)是用戶手寫的,當(dāng)children只有一個節(jié)點的時候,Vue.js從接口層面允許用戶把children寫成基礎(chǔ)類型用來創(chuàng)建單個簡單的文本節(jié)點,這種情況會調(diào)用createTextVNode創(chuàng)建一個文本節(jié)點的VNode;另一個場景是當(dāng)編譯slotv-for 的時候會產(chǎn)生嵌套數(shù)組的情況,會調(diào)用normalizeArrayChildren方法,接下來看一下它的實現(xiàn):

function normalizeArrayChildren (children: any, nestedIndex?: string): Array<VNode> {
  const res = []
  let i, c, lastIndex, last
  for (i = 0; i < children.length; i++) {
    c = children[i]
    if (isUndef(c) || typeof c === 'boolean') continue
    lastIndex = res.length - 1
    last = res[lastIndex]
    //  nested
    if (Array.isArray(c)) {
      if (c.length > 0) {
        c = normalizeArrayChildren(c, `${nestedIndex || ''}_${i}`)
        // merge adjacent text nodes
        if (isTextNode(c[0]) && isTextNode(last)) {
          res[lastIndex] = createTextVNode(last.text + (c[0]: any).text)
          c.shift()
        }
        res.push.apply(res, c)
      }
    } else if (isPrimitive(c)) {
      if (isTextNode(last)) {
        // merge adjacent text nodes
        // this is necessary for SSR hydration because text nodes are
        // essentially merged when rendered to HTML strings
        res[lastIndex] = createTextVNode(last.text + c)
      } else if (c !== '') {
        // convert primitive to vnode
        res.push(createTextVNode(c))
      }
    } else {
      if (isTextNode(c) && isTextNode(last)) {
        // merge adjacent text nodes
        res[lastIndex] = createTextVNode(last.text + c.text)
      } else {
        // default key for nested array children (likely generated by v-for)
        if (isTrue(children._isVList) &&
          isDef(c.tag) &&
          isUndef(c.key) &&
          isDef(nestedIndex)) {
          c.key = `__vlist${nestedIndex}_${i}__`
        }
        res.push(c)
      }
    }
  }
  return res
}

normalizeArrayChildren接收2個參數(shù),children表示要規(guī)范的子節(jié)點,nestedIndex表示嵌套的索引,因為單個child可能是一個數(shù)組類型。 normalizeArrayChildren主要的邏輯就是遍歷children,獲得單個節(jié)點c,然后對c的類型判斷,如果是一個數(shù)組類型,則遞歸調(diào)用normalizeArrayChildren; 如果是基礎(chǔ)類型,則通過createTextVNode方法轉(zhuǎn)換成VNode類型;否則就已經(jīng)是VNode類型了,如果children是一個列表并且列表還存在嵌套的情況,則根據(jù)nestedIndex去更新它的key。這里需要注意一點,在遍歷的過程中,對這3種情況都做了如下處理:如果存在兩個連續(xù)的text節(jié)點,會把它們合并成一個text節(jié)點。
經(jīng)過對children的規(guī)范化,children變成了一個類型為VNodeArray

VNode的創(chuàng)建

回到createElement函數(shù),規(guī)范化children后,接下來會去創(chuàng)建一個VNode的實例:

let vnode, ns
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)
}

這里先對tag做判斷,如果是string類型,則接著判斷如果是內(nèi)置的一些節(jié)點,則直接創(chuàng)建一個普通VNode,如果是為已注冊的組件名,則通過createComponent創(chuàng)建一個組件類型的VNode,否則創(chuàng)建一個未知的標(biāo)簽的VNode。 如果是tag一個Component類型,則直接調(diào)用createComponent創(chuàng)建一個組件類型的VNode節(jié)點。對于createComponent創(chuàng)建組件類型的VNode的過程,本質(zhì)上它還是返回了一個VNode

那么至此,我們大致了解了createElement 創(chuàng)建VNode的過程,每個VNodechildrenchildren每個元素也是一個VNode,這樣就形成了一個VNode Tree,它很好的描述了我們的 DOM Tree

回到mountComponent函數(shù)的過程,我們已經(jīng)知道vm._render是如何創(chuàng)建了一個VNode,接下來就是要把這個VNode渲染成一個真實的DOM并渲染出來,這個過程是通過vm._update完成的,接下來分析一下這個過程。

update

Vue_update是實例的一個私有方法,它被調(diào)用的時機有2個,一個是首次渲染,一個是數(shù)據(jù)更新的時候。_update方法的作用是把VNode渲染成真實的DOM,它的定義在src/core/instance/lifecycle.js中:

Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
  const vm: Component = this
  const prevEl = vm.$el
  const prevVnode = vm._vnode
  const prevActiveInstance = activeInstance
  activeInstance = vm
  vm._vnode = vnode
  // Vue.prototype.__patch__ is injected in entry points
  // based on the rendering backend used.
  if (!prevVnode) {
    // initial render
    vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
  } else {
    // updates
    vm.$el = vm.__patch__(prevVnode, vnode)
  }
  activeInstance = prevActiveInstance
  // update __vue__ reference
  if (prevEl) {
    prevEl.__vue__ = null
  }
  if (vm.$el) {
    vm.$el.__vue__ = vm
  }
  // if parent is an HOC, update its $el as well
  if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
    vm.$parent.$el = vm.$el
  }
  // updated hook is called by the scheduler to ensure that children are
  // updated in a parent's updated hook.
}

_update的核心就是調(diào)用vm.__patch__方法,這個方法實際上在不同的平臺,比如web和weex上的定義是不一樣的,因此在web平臺中它的定義在src/platforms/web/runtime/index.js中:

Vue.prototype.__patch__ = inBrowser ? patch : noop

可以看到,甚至在web平臺上,是否是服務(wù)端渲染也會對這個方法產(chǎn)生影響。因為在服務(wù)端渲染中,沒有真實的瀏覽器DOM環(huán)境,所以不需要把VNode最終轉(zhuǎn)換成DOM,因此是一個空函數(shù),而在瀏覽器端渲染中,它指向了patch方法,它的定義在src/platforms/web/runtime/patch.js中:

import * as nodeOps from 'web/runtime/node-ops'
import { createPatchFunction } from 'core/vdom/patch'
import baseModules from 'core/vdom/modules/index'
import platformModules from 'web/runtime/modules/index'

// the directive module should be applied last, after all
// built-in modules have been applied.
const modules = platformModules.concat(baseModules)

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

該方法的定義是調(diào)用createPatchFunction方法的返回值,這里傳入了一個對象,包含nodeOps參數(shù)和modules參數(shù)。其中,nodeOps封裝了一系列DOM操作的方法,modules定義了一些模塊的鉤子函數(shù)的實現(xiàn),來看一下createPatchFunction的實現(xiàn),它定義在src/core/vdom/patch.js中:

const hooks = ['create', 'activate', 'update', 'remove', 'destroy']

export function createPatchFunction (backend) {
  let i, j
  const cbs = {}

  const { modules, nodeOps } = backend

  for (i = 0; i < hooks.length; ++i) {
    cbs[hooks[i]] = []
    for (j = 0; j < modules.length; ++j) {
      if (isDef(modules[j][hooks[i]])) {
        cbs[hooks[i]].push(modules[j][hooks[i]])
      }
    }
  }

  // ...

  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
          oldVnode = emptyNodeAt(oldVnode)
        }

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

        // create new node
        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內(nèi)部定義了一系列的輔助方法,最終返回了一個patch方法,這個方法就賦值給了vm._update函數(shù)里調(diào)用的vm.__patch__

在介紹patch的方法實現(xiàn)之前,我們可以思考一下為何Vue.js源碼繞了這么一大圈,把相關(guān)代碼分散到各個目錄。因為patch是平臺相關(guān)的,在Web和Weex環(huán)境,它們把虛擬DOM映射到“平臺DOM”的方法是不同的,并且對“DOM”包括的屬性模塊創(chuàng)建和更新也不盡相同。因此每個平臺都有各自的nodeOpsmodules,它們的代碼需要托管在src/platforms這個大目錄下。

而不同平臺的patch的主要邏輯部分是相同的,所以這部分公共的部分托管在core這個大目錄下。差異化部分只需要通過參數(shù)來區(qū)別,這里用到了一個函數(shù)柯里化的技巧,通過createPatchFunction把差異化參數(shù)提前固化,這樣不用每次調(diào)用patch的時候都傳遞nodeOpsmodules了,這種編程技巧也非常值得學(xué)習(xí)。

在這里,nodeOps表示對“平臺 DOM”的一些操作方法,modules表示平臺的一些模塊,它們會在整個patch過程的不同階段執(zhí)行相應(yīng)的鉤子函數(shù)。
回到patch方法本身,它接收4個參數(shù),oldVnode表示舊的VNode節(jié)點,它也可以不存在或者是一個DOM對象;vnode表示執(zhí)行_render后返回的VNode的節(jié)點;hydrating表示是否是服務(wù)端渲染;removeOnly是給transition-group用的。
先來回顧我們的例子:

var app = new Vue({
  el: '#app',
  render: function (createElement) {
    return createElement('div', {
      attrs: {
        id: 'app'
      },
    }, this.message)
  },
  data: {
    message: 'Hello Vue!'
  }
})

然后我們在vm._update的方法里是這么調(diào)用patch方法的:

// initial render
vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)

結(jié)合我們的例子,我們的場景是首次渲染,所以在執(zhí)行patch函數(shù)的時候,傳入的vm.$el對應(yīng)的是例子中idapp的DOM對象,這個也就是我們在index.html模板中寫的<div id="app">vm.$el的賦值是在之前mountComponent函數(shù)做的,vnode對應(yīng)的是調(diào)用render函數(shù)的返回值,hydrating在非服務(wù)端渲染情況下為falseremoveOnlyfalse
確定了這些入?yún)⒑螅覀兓氐?code>patch函數(shù)的執(zhí)行過程,看幾個關(guān)鍵步驟。

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
    oldVnode = emptyNodeAt(oldVnode)
  }

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

  // create new node
  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)
  )
}

由于我們傳入的oldVnode實際上是一個DOM container,所以isRealElementtrue,接下來又通過emptyNodeAt方法把oldVnode轉(zhuǎn)換成VNode對象,然后再調(diào)用createElm方法,這個方法在這里非常重要,來看一下它的實現(xiàn):

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
  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
        )
      }
    }

    vnode.elm = vnode.ns
      ? nodeOps.createElementNS(vnode.ns, tag)
      : nodeOps.createElement(tag, vnode)
    setScope(vnode)

    /* istanbul ignore if */
    if (__WEEX__) {
      // ...
    } else {
      createChildren(vnode, children, insertedVnodeQueue)
      if (isDef(data)) {
        invokeCreateHooks(vnode, insertedVnodeQueue)
      }
      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)
  }
}

createElm的作用是通過虛擬節(jié)點創(chuàng)建真實的DOM并插入到它的父節(jié)點中。 我們來看一下它的一些關(guān)鍵邏輯,createComponent方法目的是嘗試創(chuàng)建子組件,在當(dāng)前這個case下它的返回值為false;接下來判斷vnode是否包含tag,如果包含,先簡單對tag的合法性在非生產(chǎn)環(huán)境下做校驗,看是否是一個合法標(biāo)簽;然后再去調(diào)用平臺DOM的操作去創(chuàng)建一個占位符元素。

vnode.elm = vnode.ns
  ? nodeOps.createElementNS(vnode.ns, tag)
  : nodeOps.createElement(tag, vnode)

接下來調(diào)用createChildren方法去創(chuàng)建子元素:

createChildren(vnode, children, insertedVnodeQueue)

function createChildren (vnode, children, insertedVnodeQueue) {
  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)) {
    nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(String(vnode.text)))
  }
}

createChildren的邏輯很簡單,實際上是遍歷子虛擬節(jié)點,遞歸調(diào)用createElm,這是一種常用的深度優(yōu)先的遍歷算法,這里要注意的一點是在遍歷過程中會把vnode.elm作為父容器的DOM節(jié)點占位符傳入。
接著再調(diào)用invokeCreateHooks方法執(zhí)行所有的create的鉤子并把vnodev pushinsertedVnodeQueue中。

 if (isDef(data)) {
  invokeCreateHooks(vnode, insertedVnodeQueue)
}

function invokeCreateHooks (vnode, insertedVnodeQueue) {
  for (let i = 0; i < cbs.create.length; ++i) {
    cbs.create[i](emptyNode, vnode)
  }
  i = vnode.data.hook // Reuse variable
  if (isDef(i)) {
    if (isDef(i.create)) i.create(emptyNode, vnode)
    if (isDef(i.insert)) insertedVnodeQueue.push(vnode)
  }
}

最后調(diào)用insert方法把DOM插入到父節(jié)點中,因為是遞歸調(diào)用,子元素會優(yōu)先調(diào)用insert,所以整個vnode樹節(jié)點的插入順序是先子后父。來看一下insert方法,它的定義在src/core/vdom/patch.js上。

insert(parentElm, vnode.elm, refElm)

function insert (parent, elm, ref) {
  if (isDef(parent)) {
    if (isDef(ref)) {
      if (ref.parentNode === parent) {
        nodeOps.insertBefore(parent, elm, ref)
      }
    } else {
      nodeOps.appendChild(parent, elm)
    }
  }
}

insert邏輯很簡單,調(diào)用一些nodeOps把子節(jié)點插入到父節(jié)點中,這些輔助方法定義在src/platforms/web/runtime/node-ops.js中:

export function insertBefore (parentNode: Node, newNode: Node, referenceNode: Node) {
  parentNode.insertBefore(newNode, referenceNode)
}

export function appendChild (node: Node, child: Node) {
  node.appendChild(child)
}

其實就是調(diào)用原生DOM的API進行DOM操作。
createElm過程中,如果vnode節(jié)點不包含tag,則它有可能是一個注釋或者純文本節(jié)點,可以直接插入到父元素中。在我們這個例子中,最內(nèi)層就是一個文本 vnode,它的text值取的就是之前的this.message的值Hello Vue!

再回到patch方法,首次渲染我們調(diào)用了createElm方法,這里傳入的parentElmoldVnode.elm的父元素,在我們的例子是id#app div的父元素,也就是body;實際上整個過程就是遞歸創(chuàng)建了一個完整的DOM樹并插入到body上。
最后,我們根據(jù)之前遞歸createElm生成的vnode插入順序隊列,執(zhí)行相關(guān)的insert鉤子函數(shù)。

總結(jié)

那么至此我們從主線上把模板和數(shù)據(jù)如何渲染成最終的DOM的過程分析完畢了,我們可以通過下圖更直觀地看到從初始化Vue到最終渲染的整個過程。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容