Vue DOM Diff算法詳解

前言

本篇文章能帶給你以下內容:javascript

- 瞭解key屬性在diff算法中的的做用,以及咱們在代碼中改如何正確的給key賦值
- 深刻diff算法的核心,理解「同層對比」究竟是個什麼鬼
複製代碼

patch 函數

代碼位於:vue項目的src/core/vdom/patch.jsvue

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
  }
複製代碼

處理流程大體分爲以下步驟:java

- 當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裏面判斷同一個節點是經過:node

  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()api

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)
    }
  }
複製代碼

對比的整體思路就是:頭對頭,尾對尾,頭對尾,尾對頭app

  1. 頭對頭:oldStartVnode和newStartVnode
  2. 尾對尾:oldEndVnode和newEndVnode
  3. 頭對尾:oldStartVnode和newEndVnode
  4. 尾對頭:oldEndVnode和newStartVnode

question: 爲何會有頭對尾,尾對頭這種對比? answer: 這樣能夠更快的處理數組的reverse()這種狀況dom

若是以上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:既然到第三步就已經完成了,那爲甚還會有多餘的四、五、六、7步驟?

answer: while循環的跳出依據是:oldChildren循環完成且newChildren也循環完成,因此會出現如此現象。這樣能保證兩個children中的全部節點都遍歷到

總結

到這裏vue dom diff算法基本算講完了,總結爲以下幾點:

  1. 列表中key值的正確設定能夠提示dom diff的效率以及正確性
  2. 元素同級別對比時,文本節點的操做是最簡便的,直接替換文本內容便可。其餘節點須要經過sameVnode()進行比對後操做
  3. 子元素列表進行對比時:頭對頭、尾對尾、頭對尾、尾對頭,依次縮小對比範圍,直至兩個列表都遍歷完成
相關文章
相關標籤/搜索