理解Vue2.5中diff算法

vue是現在主流前端框架之一,採用了很多高級特性,如虛擬DOM,那麼它是如何批量更新的,我們一起來了解下。

數據變化,如何更新dom

DOM“天生就慢”,所以前端各大框架都提供了對DOM操作進行優化的辦法,Angular中的是髒值檢查,React首先提出了Virtual Dom,Vue2.0也加入了Virtual Dom,與React類似。

要知道渲染真實DOM的開銷是很大的,比如有時候我們修改了某個數據,如果直接渲染到真實dom上會引起整個dom樹的重繪和重排,有沒有可能我們只更新我們修改的那一小塊dom而不要更新整個dom呢?diff算法能夠幫助我們。

我們先根據真實DOM生成一顆virtual DOM,當virtual DOM某個節點的數據改變後會生成一個新的Vnode,然後Vnode和oldVnode作對比,發現有不一樣的地方就直接修改在真實的DOM上,然後使oldVnode的值爲Vnode。

diff的過程就是調用名爲patch的函數,比較新舊節點,一邊比較一邊給真實的DOM打補丁。

虛擬dom與真實dom

真實dom

<div>
    <p>111</p>
</div>

對應的virtual DOM(僞代碼)

var Vnode = {
    tag: 'div',
    children: [
        { tag: 'p', text: '111' }
    ]
};

diff對比方式

在採取diff算法比較新舊節點的時候,比較只會在同層級進行, 不會跨層級比較。

<div>
    <p>123</p>
</div>

<div>
    <span>456</span>
</div>

上面的代碼會分別比較同一層的兩個div以及第二層的p和span,但是不會拿div和span作比較。在別處看到的一張很形象的圖:

 

diff-compare.png

diff流程圖

當數據發生改變時,set方法會讓調用Dep.notify通知所有訂閱者Watcher,訂閱者就會調用patch給真實的DOM打補丁,更新相應的視圖。

 

diff.png

VNode對象

一個VNode的實例包含了以下屬性,這部分代碼在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;
  functionalContext: Component | void; // real context vm for functional nodes
  functionalOptions: ?ComponentOptions; // for SSR caching
  functionalScopeId: ?string; // functioanl scope id support
  • tag: 當前節點的標籤名
  • data: 當前節點的數據對象,具體包含哪些字段可以參考vue源碼types/vnode.d.ts中對VNodeData的定義
  • children: 數組類型,包含了當前節點的子節點
  • text: 當前節點的文本,一般文本節點或註釋節點會有該屬性
  • elm: 當前虛擬節點對應的真實的dom節點
  • ns: 節點的namespace
  • context: 編譯作用域
  • functionalContext: 函數化組件的作用域
  • key: 節點的key屬性,用於作爲節點的標識,有利於patch的優化
  • componentOptions: 創建組件實例時會用到的選項信息
  • child: 當前節點對應的組件實例
  • parent: 組件的佔位節點
  • raw: raw html
  • isStatic: 靜態節點的標識
  • isRootInsert: 是否作爲根節點插入,被包裹的節點,該屬性的值爲false
  • isComment: 當前節點是否是註釋節點
  • isCloned: 當前節點是否爲克隆節點
  • isOnce: 當前節點是否有v-once指令

VNode的分類

VNode可以理解爲VueVirtual Dom的一個基類,通過VNode構造函數生成的VNnode實例可爲如下幾類:

  • EmptyVNode: 沒有內容的註釋節點
  • TextVNode: 文本節點
  • ElementVNode: 普通元素節點
  • ComponentVNode: 組件節點
  • CloneVNode: 克隆節點,可以是以上任意類型的節點,唯一的區別在於isCloned屬性爲true

具體Diff分析

來看看patch是怎麼打補丁的(代碼只保留核心部分)

function patch (oldVnode, vnode) {
    // some code
    if (sameVnode(oldVnode, vnode)) {
        patchVnode(oldVnode, vnode)
    } else {
        const oEl = oldVnode.el // 當前oldVnode對應的真實元素節點
        let parentEle = api.parentNode(oEl)  // 父元素
        createEle(vnode)  // 根據Vnode生成新元素
        if (parentEle !== null) {
            api.insertBefore(parentEle, vnode.el, api.nextSibling(oEl)) // 將新元素添加進父元素
            api.removeChild(parentEle, oldVnode.el)  // 移除以前的舊元素節點
            oldVnode = null
        }
    }
    // some code 
    return vnode
}

patch函數接收兩個參數oldVnode和Vnode分別代表新的節點和之前的舊節點
判斷兩節點是否值得比較,值得比較則執行patchVnode

function sameVnode (a, b) {
  return (
    a.key === b.key &&  // key值
    a.tag === b.tag &&  // 標籤名
    a.isComment === b.isComment &&  // 是否爲註釋節點
    // 是否都定義了data,data包含一些具體信息,例如onclick , style
    isDef(a.data) === isDef(b.data) &&  
    sameInputType(a, b) // 當標籤是<input>的時候,type必須相同
  )
}

不值得比較則用Vnode替換oldVnode
如果兩個節點都是一樣的,那麼就深入檢查他們的子節點。如果兩個節點不一樣那就說明Vnode完全被改變了,就可以直接替換oldVnode。
雖然這兩個節點不一樣但是他們的子節點一樣怎麼辦?別忘了,diff可是逐層比較的,如果第一層不一樣那麼就不會繼續深入比較第二層了。

patchVnode

當我們確定兩個節點值得比較之後我們會對兩個節點指定patchVnode方法。那麼這個方法做了什麼呢?

patchVnode (oldVnode, vnode) {
    const el = vnode.el = oldVnode.el
    let i, oldCh = oldVnode.children, ch = vnode.children
    if (oldVnode === vnode) return
    if (oldVnode.text !== null && vnode.text !== null && oldVnode.text !== vnode.text) {
        api.setTextContent(el, vnode.text)
    }else {
        updateEle(el, vnode, oldVnode)
        if (oldCh && ch && oldCh !== ch) {
            updateChildren(el, oldCh, ch)
        }else if (ch){
            createEle(vnode) //create el's children dom
        }else if (oldCh){
            api.removeChildren(el)
        }
    }
}

這個函數做了以下事情:

  • 找到對應的真實dom,稱爲el
  • 判斷Vnode和oldVnode是否指向同一個對象,如果是,那麼直接return
  • 如果他們都有文本節點並且不相等,那麼將el的文本節點設置爲Vnode的文本節點。
  • 如果oldVnode有子節點而Vnode沒有,則刪除el的子節點
  • 如果oldVnode沒有子節點而Vnode有,則將Vnode的子節點真實化之後添加到el
  • 如果兩者都有子節點,則執行updateChildren函數比較子節點,這一步很重要
    其他幾個點都很好理解,我們詳細來講一下updateChildren

updateChildren

updataChildren是Diff算法的核心,所以本文對updataChildren進行了圖文的分析。

function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
    let oldStartIdx = 0 // 舊頭索引
    let newStartIdx = 0 // 新頭索引
    let oldEndIdx = oldCh.length - 1 // 舊尾索引
    let newEndIdx = newCh.length - 1 // 新尾索引
    let oldStartVnode = oldCh[0] // oldVnode的第一個child
    let oldEndVnode = oldCh[oldEndIdx] // oldVnode的最後一個child
    let newStartVnode = newCh[0] // newVnode的第一個child
    let newEndVnode = newCh[newEndIdx] // newVnode的最後一個child
    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

    // 如果oldStartVnode和oldEndVnode重合,並且新的也都重合了,證明diff完了,循環結束
    while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
      // 如果oldVnode的第一個child不存在
      if (isUndef(oldStartVnode)) {
        // oldStart索引右移
        oldStartVnode = oldCh[++oldStartIdx] // Vnode has been moved left

      // 如果oldVnode的最後一個child不存在
      } else if (isUndef(oldEndVnode)) {
        // oldEnd索引左移
        oldEndVnode = oldCh[--oldEndIdx]

      // oldStartVnode和newStartVnode是同一個節點
      } else if (sameVnode(oldStartVnode, newStartVnode)) {
        // patch oldStartVnode和newStartVnode, 索引左移,繼續循環
        patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue)
        oldStartVnode = oldCh[++oldStartIdx]
        newStartVnode = newCh[++newStartIdx]

      // oldEndVnode和newEndVnode是同一個節點
      } else if (sameVnode(oldEndVnode, newEndVnode)) {
        // patch oldEndVnode和newEndVnode,索引右移,繼續循環
        patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue)
        oldEndVnode = oldCh[--oldEndIdx]
        newEndVnode = newCh[--newEndIdx]

      // oldStartVnode和newEndVnode是同一個節點
      } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
        // patch oldStartVnode和newEndVnode
        patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue)
        // 如果removeOnly是false,則將oldStartVnode.eml移動到oldEndVnode.elm之後
        canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm))
        // oldStart索引右移,newEnd索引左移
        oldStartVnode = oldCh[++oldStartIdx]
        newEndVnode = newCh[--newEndIdx]

      // 如果oldEndVnode和newStartVnode是同一個節點
      } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
        // patch oldEndVnode和newStartVnode
        patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue)
        // 如果removeOnly是false,則將oldEndVnode.elm移動到oldStartVnode.elm之前
        canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm)
        // oldEnd索引左移,newStart索引右移
        oldEndVnode = oldCh[--oldEndIdx]
        newStartVnode = newCh[++newStartIdx]

      // 如果都不匹配
      } else {
        if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx)

        // 嘗試在oldChildren中尋找和newStartVnode的具有相同的key的Vnode
        idxInOld = isDef(newStartVnode.key)
          ? oldKeyToIdx[newStartVnode.key]
          : findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx)

        // 如果未找到,說明newStartVnode是一個新的節點
        if (isUndef(idxInOld)) { // New element
          // 創建一個新Vnode
          createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm)

        // 如果找到了和newStartVnodej具有相同的key的Vnode,叫vnodeToMove
        } else {
          vnodeToMove = oldCh[idxInOld]
          /* istanbul ignore if */
          if (process.env.NODE_ENV !== 'production' && !vnodeToMove) {
            warn(
              'It seems there are duplicate keys that is causing an update error. ' +
              'Make sure each v-for item has a unique key.'
            )
          }

          // 比較兩個具有相同的key的新節點是否是同一個節點
          //不設key,newCh和oldCh只會進行頭尾兩端的相互比較,設key後,除了頭尾兩端的比較外,還會從用key生成的對象oldKeyToIdx中查找匹配的節點,所以爲節點設置key可以更高效的利用dom。
          if (sameVnode(vnodeToMove, newStartVnode)) {
            // patch vnodeToMove和newStartVnode
            patchVnode(vnodeToMove, newStartVnode, insertedVnodeQueue)
            // 清除
            oldCh[idxInOld] = undefined
            // 如果removeOnly是false,則將找到的和newStartVnodej具有相同的key的Vnode,叫vnodeToMove.elm
            // 移動到oldStartVnode.elm之前
            canMove && nodeOps.insertBefore(parentElm, vnodeToMove.elm, oldStartVnode.elm)

          // 如果key相同,但是節點不相同,則創建一個新的節點
          } else {
            // same key but different element. treat as new element
            createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm)
          }
        }

        // 右移
        newStartVnode = newCh[++newStartIdx]
      }
    }

先說一下這個函數做了什麼

將Vnode的子節點Vch和oldVnode的子節點oldCh提取出來
oldCh和vCh各有兩個頭尾的變量StartIdx和EndIdx,它們的2個變量相互比較,一共有4種比較方式。如果4種比較都沒匹配,如果設置了key,就會用key進行比較,在比較的過程中,變量會往中間靠,一旦StartIdx>EndIdx表明oldCh和vCh至少有一個已經遍歷完了,就會結束比較。
圖解updateChildren
終於來到了這一部分,上面的總結相信很多人也看得一臉懵逼,下面我們好好說道說道。(這都是我自己畫的,求推薦好用的畫圖工具...)

粉紅色的部分爲oldCh和vCh

 

vnode.png

我們將它們取出來並分別用s和e指針指向它們的頭child和尾child

 

patchnode.png

現在分別對oldS、oldE、S、E兩兩做sameVnode比較,有四種比較方式,當其中兩個能匹配上那麼真實dom中的相應節點會移到Vnode相應的位置,這句話有點繞,打個比方

如果是oldS和E匹配上了,那麼真實dom中的第一個節點會移到最後
如果是oldE和S匹配上了,那麼真實dom中的最後一個節點會移到最前,匹配上的兩個指針向中間移動
如果四種匹配沒有一對是成功的,那麼遍歷oldChild,S挨個和他們匹配,匹配成功就在真實dom中將成功的節點移到最前面,如果依舊沒有成功的,那麼將S對應的節點插入到dom中對應的oldS位置,oldS和S指針向中間移動。

再配個圖

 

patchnode2.png

第一步
oldS = a, oldE = d;
S = a, E = b;
oldS和S匹配,則將dom中的a節點放到第一個,已經是第一個了就不管了,此時dom的位置爲:a b d

第二步
oldS = b, oldE = d;
S = c, E = b;
oldS和E匹配,就將原本的b節點移動到最後,因爲E是最後一個節點,他們位置要一致,這就是上面說的:當其中兩個能匹配上那麼真實dom中的相應節點會移到Vnode相應的位置,此時dom的位置爲:a d b

第三步
oldS = d, oldE = d;
S = c, E = d;
oldE和E匹配,位置不變此時dom的位置爲:a d b

第四步
oldS++;
oldE--;
oldS > oldE;
遍歷結束,說明oldCh先遍歷完。就將剩餘的vCh節點根據自己的的index插入到真實dom中去,此時dom位置爲:a c d b

一次模擬完成。

這個匹配過程的結束有兩個條件:

  • oldS > oldE表示oldCh先遍歷完,那麼就將多餘的vCh根據index添加到dom中去(如上圖)
  • S > E表示vCh先遍歷完,那麼就在真實dom中將區間爲[oldS, oldE]的多餘節點刪掉
    如下圖,新dom比舊dom少,最終爲:a b e

     

    patchnode3.png

再來一個例子,最終dom順序爲:a e b f

 

patchnode4.png

當這些節點sameVnode成功後就會緊接着執行patchVnode了,可以看一下上面的代碼

if (sameVnode(oldStartVnode, newStartVnode)) {
    patchVnode(oldStartVnode, newStartVnode)
}

就這樣層層遞歸下去,直到將oldVnode和Vnode中的所有子節點比對完。也將dom的所有補丁都打好啦。那麼現在再回過去看updateChildren的代碼會不會容易很多呢?



參考資料,VUE入門到實戰項目教程,只需要0.1:https://ke.qq.com/course/391236?tuin=6fd9e576 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章