Vue2源码解析-diff算法理解

100 阅读2分钟

我们在改变某个属性值的时候,组件会发生了更新,执行vm._update⽅法,它定义在vue/src/core/instance/lifecycle.js

Snipaste_2022-04-03_19-23-36.png

组件更新至执行vm.$el = vm.__patch__(prevVnode, vnode),它仍然会调⽤patch方法,定义在vue/src/core/vdom/patch.js

Snipaste_2022-04-03_19-27-59.png

这里会至执行sameVNode(oldVnode, vnode),判断oldVnodevnode是否相同来决定⾛不同的更新逻辑

Snipaste_2022-04-03_19-30-27.png

该方法主要是比较如果两个vnodekey不相等,则是不同的;否则继续判断对于同步组件,则判断 isCommentdatainput类型等是否相同,对于异步组件,则判断asyncFactory是否相同。所以根据新旧vnode是否为sameVnode会⾛到不同的更新逻辑。

对于新旧节点不同:

本质上是替换已存在的节点,⼤致分为3

  1. 创建新节点,并插入到旧节点的父DOM

Snipaste_2022-04-03_19-35-06.png

  1. 更新⽗的占位符节点

Snipaste_2022-04-03_19-37-12.png

找到当前vnode的⽗的占位符节点,先执⾏各个moduledestroy钩⼦函数,如果当前占位符是⼀个可挂载的节点,则执⾏modulecreate钩⼦函数

  1. 删除旧节点

Snipaste_2022-04-03_19-39-49.png

对于新旧节点相同:

会调用patchVNode,定义在vue/src/core/vdom/patch.js

Snipaste_2022-04-03_19-42-28.png

patchVnode的作⽤就是把新的vnodepatch到旧的vnode上,主要分四步:

1.执⾏prepatch钩⼦函数

Snipaste_2022-04-03_19-44-05.png

当更新的vnode是⼀个组件vnode的时候,会执⾏prepatch的⽅法,prepatch⽅法就是拿到新的 vnode的组件配置以及组件实例,去执⾏updateChildComponent⽅法,updateChildComponent主要将的vnode对应的实例vm的⼀系列属性更新,包括占位符vm.$vnode的更新、slot的更新,listeners的更新,props的更新等等

2.执⾏update钩⼦函数

Snipaste_2022-04-03_19-47-20.png

在执⾏完新的vnodeprepatch钩⼦函数,会执⾏所有moduleupdate钩⼦函数以及⽤户⾃定义 update钩⼦函数

3.完成patch过程

Snipaste_2022-04-03_19-50-02.png

如果vnode是个⽂本节点且新旧⽂本不相同,则直接替换⽂本内容。如果不是⽂本节点,则判断它们的⼦节点,并分了⼏种情况处理:

  • oldChch 都存在且不相时,使⽤updateChildren函数来更新⼦节点

  • 如果只有 ch 存在,表⽰旧节点不需要了。如果旧的节点是⽂本节点则先将节点的⽂本清除,然后通过 addVnodesch批量插⼊到新节点elm

  • 如果只有oldC 存在,表⽰更新的是空节点,则需要将旧的节点通过removeVnodes全部清除。

  • 当只有旧节点是⽂本节点的时候,则清除其节点⽂本内容

4.执⾏postpatch钩⼦函数

Snipaste_2022-04-03_19-54-55.png

整个最复杂的部分是updateChildren

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

我们通过

总结: 组件更新的过程核⼼就是新旧 vnode diff,对新旧节点相同以及不同的情况分别做不同的处理。新旧节点不同的更新流程是创建新节点->更新⽗占位符节点->删除旧节点;⽽新旧节点相同的更新流程是去获取它们的 children,根据不同情况做不同的更新逻辑。最复杂的情况是新旧节点相同且它们都存在⼦节组件更新点,那么会执⾏ updateChildren 逻辑,这块⼉可以借助画图的⽅式配合理解