• What is the virtual DOM

An object that represents a DOM tree, usually containing the tag name, tag attributes, event listeners, child elements, and other attributes

  • What the virtual DOM looks like
React const vNode = {key: null, props: {children: [// children: {type: 'span',...}, {type: 'span,...}], the className: "red" / / label attribute onClick: () = > {}} / / events, ref: null, type: "div", / / tag name or component name... }Copy the code
Const vNode = {tag: "div", // tag name or component name data: {class: "red", // tags on: {click: () = > {}}} / / event, children: [/ / the child elements are {tag: "span",...}, {} tag: "span",...],... }Copy the code
  • What are the advantages of the virtual DOM
  1. Reduce DOM manipulation

The virtual DOM can combine multiple operations into one operation, so if you add 1000 nodes, but do it one after another (reduce the frequency), the virtual DOM can use DOM diff to eliminate unnecessary operations, like if you add 1000 nodes, In fact, only 10 are new (reduced) 2. The cross-platform virtual DOM can become not only a DOM, but also applets, iOS apps, and Android apps, because the virtual DOM is essentially just a JS object

  • How do I create a virtual DOM
React.createElement
createElement('div',{className:'red',onClick:()=> {}},[
    createElement('span', {}, 'span1'),
    createElement('span', {}, 'span2')
  ]
)
Copy the code
H ('div', {class: 'red', on: {click: () => { } }, }, [h('span',{},'span1'), h('span', {}, 'span2'])Copy the code
  • Simplify the creation of virtual DOM
React JSX
<div className="red" onClick="{()=> {}}">
    <span>span1</span>
    <span>span2</span>
</div>

Copy the code
Vue Template
h('div', {
  class: 'red',
  on: {
    click: () => { }
  },
}, [h('span',{},'span1'), h('span', {}, 'span2'])

Copy the code
  • Disadvantages of the virtual DOM

Additional creation functions, such as createElement or h, are required, but can be simplified to XML using JSX

The comparison algorithm of DOM diff virtual DOM is a function, which is called patch patches = patch(oldVNode, newVNode).

  • The probable logic of DOM Diff

Compare the old and new trees layer by layer to find which nodes need to be updated. If the node is a Component, look at Component diff. If the node is a tag, look at Element diff. If the component type is different, replace it directly (delete the old one). If the component type is the same, only update the attribute. Then go into the component and do the Tree diff. If it’s the same, just update the attribute and then go into the tag descendant and do Tree diff

  • DOM Diff’s weaknesses

Sibling nodes in contrast there are bugs reference reading Vue2.0 v – for: what is the key to use www.zhihu.com/question/61…