VueThe virtualDOMRefer to thesnabbdom


1. What is Virtual DOM

  • Virtual DOM(Virtual DOM) is a common JS object to describe the DOM object
  • Real DOM members – too many attributes
  • Use the Virtual DOM to describe the real DOM
{
    sel: "div".data: {},
    children: undefined.text: "Hello Virtual DOM".elm: undefined.key: undefined
}
Copy the code

2. Why use Virtual DOM

  • The MVVM framework addresses view and state synchronization issues
  • The template engine can simplify view operations without being able to track state
  • The virtual DOM tracks state changes

Virtual-dom motivation description – see Virtual-dom on Github

  • The virtual DOM can maintain the state of the program, keeping track of the last state
  • Update the real DOM by comparing the two states

3. The role of the virtual DOM

  • Maintain the relationship between views and states
  • Improved rendering performance in complex view situations
  • cross-platform
    • Browser platforms render the DOM
    • Server render SSR (nuxt.js/Next-js)
    • Weex/React Native
    • Small programs (MPvue /uni-app), etc

Virtual DOM library

  • Snabbdom

    • The virtual DOM used internally in vue.js 2.x is a modified Snabbdom
    • Approximately 200SLOC(single line of code)
    • Extensible through modules
    • The source code to useTypeScriptThe development of
    • One of the fastest Virtual DOM
  • virtual-dom

Diffalgorithm

Quick memory is as follows: four kinds of match lookup 1. Old before new before 2. Old after new after 3. 4=> (if this item occurs, then the node pointing to the old before is moved to the old before)Copy the code
  • Start and End nodes – [old before new before, old after new after]

  • Old Start node/New End node – [Old before new after]

  • Old end node/new start node

  • None of the above four cases

  • End of the cycle
    • The loop ends when all children of the old node are traversed first (oldStartIdx < oldEndIdx)
    • All children of the new node are traversed first (newStartIdx > newEndIdx), and the loop ends

Four hit lookups

The old and the new and the old and the new and the old and the new

3=> (if this happens, then the node pointing to the old before moves to the old after)

else if (sameVnode(oldStartVnode, newEndVnode)) {
    patchVnode(oldStartVnode, newEndVnode)
    api.insertBefore(parentElm, oldStartVnode.elm, api.nextSibling(oldEndVnode.ele))
}
Copy the code

4=> (if this happens, then the node pointing to the old after, moves the old before before)

else if (sameVnode(oldEndVnode, newStartVnode)) {
    patchVnode(oldEndVnode, newStartVnode)
    api.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm)
}
Copy the code