Vue DOM Diff算法详解

·  阅读 2193

前言

本篇文章能带给你如下内容:

- 了解key属性在diff算法中的的作用,以及我们在代码中改如何正确的给key赋值
- 深入diff算法的核心,理解“同层对比”到底是个什么鬼
复制代码

patch 函数

代码位于:vue项目的src/core/vdom/patch.js


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, null, null, 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([oldVnode], 0, 0)
        } else if (isDef(oldVnode.tag)) {
          invokeDestroyHook(oldVnode)
        }
      }
    }

    invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch)
    return vnode.elm
  }
复制代码

处理流程大致分为如下步骤:

- 当vnode不存在,但是oldVnode存在时需要: 移除oldVnode
- 当oldVnode不存在,但是vnode存在时需要: 创建vnode
- 当vnode和oldVnode均存在时,又分如下情况:
    1.如果vnode和oldVnode是 **同一个** (通过sameVnode()进行比对,后面会详细讲到这个方法)结点,则进行后续对比工作:通过调用patchVnode(),这个方法右面也会详解
    2. 如果vnode和oldVnode是 **不是同一个** 结点,那么根据vnode创建新元素并挂载至oldVnode的父元素下,同时还需要销毁oldVnode
复制代码

sameVnode()

function sameVnode (a, b) {
  return (
    a.key === b.key && (
      (
        a.tag === b.tag &&
        a.isComment === b.isComment &&
        isDef(a.data) === isDef(b.data) &&
        sameInputType(a, b)
      ) || (
        isTrue(a.isAsyncPlaceholder) &&
        a.asyncFactory === b.asyncFactory &&
        isUndef(b.asyncFactory.error)
      )
    )
  )
}
复制代码

从这里可以的知道,vue里面判断同一个节点是通过:

  1. key值一样
  2. tag一样(node的tag,类似于dom元素的tag,只不过这个tag是vue组件的最外层包裹tag)
  3. isComment一样,这个不用太关注
  4. sameInputType(), 专门针对表单输入项进行判断的:input一样但是里面的type不一样算不同的inputType

所以从这里可以知道:key可以为vue dom diff提供辅助方法,让其快速定位是否为同一个元素,且要保证其唯一性。所以在循环中给元素的key复制最佳实践是:元素的唯一标识:id或者其他属性,而不是列表的index。使用index只会适得其反

patchVnode

根据前面的逻辑,当判断oldVnode和vnode是同一个节点之后才会调用patchVnode()

function patchVnode (
    oldVnode,
    vnode,
    insertedVnodeQueue,
    ownerArray,
    index,
    removeOnly
  ) {
    if (oldVnode === vnode) {
      return
    }

    if (isDef(vnode.elm) && isDef(ownerArray)) {
      // clone reused vnode
      vnode = ownerArray[index] = cloneVNode(vnode)
    }

    const elm = vnode.elm = oldVnode.elm

    if (isTrue(oldVnode.isAsyncPlaceholder)) {
      if (isDef(vnode.asyncFactory.resolved)) {
        hydrate(oldVnode.elm, vnode, insertedVnodeQueue)
      } else {
        vnode.isAsyncPlaceholder = true
      }
      return
    }

    // reuse element for static trees.
    // note we only do this if the vnode is cloned -
    // if the new node is not cloned it means the render functions have been
    // reset by the hot-reload-api and we need to do a proper re-render.
    if (isTrue(vnode.isStatic) &&
      isTrue(oldVnode.isStatic) &&
      vnode.key === oldVnode.key &&
      (isTrue(vnode.isCloned) || isTrue(vnode.isOnce))
    ) {
      vnode.componentInstance = oldVnode.componentInstance
      return
    }

    let i
    const data = vnode.data
    if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) {
      i(oldVnode, vnode)
    }

    const oldCh = oldVnode.children
    const ch = vnode.children
    if (isDef(data) && isPatchable(vnode)) {
      for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode)
      if (isDef(i = data.hook) && isDef(i = i.update)) i(oldVnode, vnode)
    }
    if (isUndef(vnode.text)) {
      if (isDef(oldCh) && isDef(ch)) {
        if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly)
      } else if (isDef(ch)) {
        if (process.env.NODE_ENV !== 'production') {
          checkDuplicateKeys(ch)
        }
        if (isDef(oldVnode.text)) nodeOps.setTextContent(elm, '')
        addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue)
      } else if (isDef(oldCh)) {
        removeVnodes(oldCh, 0, oldCh.length - 1)
      } else if (isDef(oldVnode.text)) {
        nodeOps.setTextContent(elm, '')
      }
    } else if (oldVnode.text !== vnode.text) {
      nodeOps.setTextContent(elm, vnode.text)
    }
    if (isDef(data)) {
      if (isDef(i = data.hook) && isDef(i = i.postpatch)) i(oldVnode, vnode)
    }
  }

复制代码

大致分为如下几个步骤:

  1. 如果新老节点引用一致,这直接返回,不用进行后续任何操作
  2. 如果是静态节点,则进行赋值:vnode.componentInstance = oldVnode.componentInstance,然后返回
  3. cbs.update[i](oldVnode, vnode),更新oldVnode的所有属性包括:attrs、class、domProps、events、style、ref、directives
  4. 如果oldVnode和vnode都有children, 且他们的children不是同一个则调用:updateChildren() 这个方法很重要,后面会讲到
  5. 如果只有vnode定义了children, 如果oldVnode定义了文本节点,那么将将当前elm的textContent设置为:'',同时调用addVnodes给当前elm新增vnode.chidlren
  6. 如果只有oldVnode定义了children,那么移除oldVnode.children
  7. 如果只有oldVnode定义了text属性,那么将当前elm的textContent设置为:''
  8. 如果oldVnode.text和vnode.text不相等,则将当前elm的textContent设置为:vnode.text

updateChildren(重点的重点)

上文讲到,当oldVnode.children 和vnode.children不相等时会调用本方法:

function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
    let oldStartIdx = 0
    let newStartIdx = 0
    let oldEndIdx = oldCh.length - 1
    let oldStartVnode = oldCh[0]
    let oldEndVnode = oldCh[oldEndIdx]
    let newEndIdx = newCh.length - 1
    let newStartVnode = newCh[0]
    let newEndVnode = newCh[newEndIdx]
    let oldKeyToIdx, idxInOld, vnodeToMove, refElm

    // removeOnly is a special flag used only by <transition-group>
    // to ensure removed elements stay in correct relative positions
    // during leaving transitions
    const canMove = !removeOnly

    if (process.env.NODE_ENV !== 'production') {
      checkDuplicateKeys(newCh)
    }

    while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
      if (isUndef(oldStartVnode)) {
        oldStartVnode = oldCh[++oldStartIdx] // Vnode has been moved left
      } else if (isUndef(oldEndVnode)) {
        oldEndVnode = oldCh[--oldEndIdx]
      } else if (sameVnode(oldStartVnode, newStartVnode)) {
        patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx)
        oldStartVnode = oldCh[++oldStartIdx]
        newStartVnode = newCh[++newStartIdx]
      } else if (sameVnode(oldEndVnode, newEndVnode)) {
        patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx)
        oldEndVnode = oldCh[--oldEndIdx]
        newEndVnode = newCh[--newEndIdx]
      } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
        patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx)
        canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm))
        oldStartVnode = oldCh[++oldStartIdx]
        newEndVnode = newCh[--newEndIdx]
      } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
        patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx)
        canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm)
        oldEndVnode = oldCh[--oldEndIdx]
        newStartVnode = newCh[++newStartIdx]
      } else {
        // idxInOld: newStartVnode 在oldCh列表中的索引
        if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx)
        idxInOld = isDef(newStartVnode.key)
          ? oldKeyToIdx[newStartVnode.key]
          : findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx)
        if (isUndef(idxInOld)) { // New element
          createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx)
        } else {
          vnodeToMove = oldCh[idxInOld]
          if (sameVnode(vnodeToMove, newStartVnode)) {
            patchVnode(vnodeToMove, newStartVnode, insertedVnodeQueue, newCh, newStartIdx)
            oldCh[idxInOld] = undefined
            canMove && nodeOps.insertBefore(parentElm, vnodeToMove.elm, oldStartVnode.elm)
          } else {
            // same key but different element. treat as new element
            createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx)
          }
        }
        newStartVnode = newCh[++newStartIdx]
      }
    }
    if (oldStartIdx > oldEndIdx) {
      refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm
      addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue)
    } else if (newStartIdx > newEndIdx) {
      removeVnodes(oldCh, oldStartIdx, oldEndIdx)
    }
  }
复制代码

对比的总体思路就是:头对头,尾对尾,头对尾,尾对头

  1. 头对头:oldStartVnode和newStartVnode
  2. 尾对尾:oldEndVnode和newEndVnode
  3. 头对尾:oldStartVnode和newEndVnode
  4. 尾对头:oldEndVnode和newStartVnode

question: 为什么会有头对尾,尾对头这种对比? answer: 这样可以更快的处理数组的reverse()这种情况

如果以上4种情况都没有get到该怎么办?

  1. else

    1.为oldCh创建一个key Map

    2.在key Map中找到newStartVnode.key的index(这里需要注意,如果我们编码时没有给出节点的key,会走下面的第三步,直接创建新元素。很显然:元素的创建比移动操作更消耗性能

    3.如果没有找到index则认为newStartVnode是一个新元素,直接创建

    4.如果找到了index,通过sameVnode()比对

     4.1 比对成功:则继续调用`patchVnode()`同时在父节点下插入newNode
     
     4.2 比对失败:(虽然他们具有相同的key,但不是同一个元素),当新元素对待,直接创建
    复制代码

1-5是一个while循环,每一次循环都会缩小对比范围,直至所有子节点均对比完成。下面用一个例子来说明。

eg:

<li v-for="letter in list" :key="letter">
    {{letter}}
</li>
复制代码

以下为list的数据结构:

before: ['A', 'B', 'C', 'D', 'E']

after: ['C', 'D', 'E', 'F', 'A', 'B']

以下为调用updateChildren()中while循环后的每一次的结果:

round1: ["C", "A", "B", "D", "E"]

round2: ["C", "D", "A", "B", "E"]

round3: ["C", "D", "E", "A", "B"]

到这里子元素的位置已经调换完成了,但是实际上后面还需有,round4/5/6/7,但是子节点的位置已经和round3一致,都是 ["C", "D", "E", "A", "B"]

question:既然到第三步就已经完成了,那为甚还会有多余的4、5、6、7步骤?

answer: while循环的跳出依据是:oldChildren循环完成且newChildren也循环完成,所以会出现如此现象。这样能保证两个children中的所有节点都遍历到

总结

到这里vue dom diff算法基本算讲完了,总结为如下几点:

  1. 列表中key值的正确设定可以提示dom diff的效率以及正确性
  2. 元素同级别对比时,文本节点的操作是最简便的,直接替换文本内容即可。其他节点需要通过sameVnode()进行比对后操作
  3. 子元素列表进行对比时:头对头、尾对尾、头对尾、尾对头,依次缩小对比范围,直至两个列表都遍历完成
分类:
前端
标签:
分类:
前端
标签: