Virtual dom
The virtual DOM is essentially a data virtual DOM and a real node
- Virtual dom
{
children: [{...}],data: {},
elm: h1,
key: undefined.sel: "h1".text: undefined
}
Copy the code
- Real nodes
< h2 > I am h2 < / h2 >Copy the code
The diff algorithm
In fact, the core of diff algorithm is dom datalization to improve performance, and the generated virtual DOM is compared with real nodes and then updated
- Compare the rules
- If the old node and the new node are not the same, the new node is added and then deleted (for example, if the old node is div and the new node is h1, h1 is created before div is deleted).
- Can only be compared at the same level, not across levels (e.g. Div and UL are at the same level, only div and UL can be compared, not li and ul can be compared)
- If the old and new nodes are the same node
- If the new node has no children, it means that the new node is a text. No matter whether the old node has children, it will be directly overwritten by the text of the new node
- If the new node has children and the old node has no children, the content of the old node will be cleared and the children of the new node will be added
- The new node has children, and the old node also has children ===> the core of the diff algorithm
- The heart of the DIff algorithm
- Old and new, the pointer is ++
- Patch content
- After the old and new, the Pointers are —
- Patch content
- Old before and new after, old before pointer ++, new after pointer —
- The content is patched, and the former child node is moved to the last node of the old node (the node moved to the last node does not count, it is the last child node of the original old node)
- Old after and new before, old after pointer –, new before pointer ++
- Patch the content, and move the old child node to the front of the first node of the old node (the node moved to the past does not count, it is the first child node of the original old node).
- Don’t meet
- Take the new child node to the old node to find
- If not, create it directly and insert it in front of the old node
- If found, move the child found in the old node to the front of the old node, and then set the position of the original child to undefined
- Take the new child node to the old node to find
- Delete or create
- Old and new, the pointer is ++
When the pointer ++ or -- encounters undefined, it skips and goes to the next one