What is the virtual Dom?
Through a real Dom node objects to save and record the page, the page when we change, will generate the corresponding new virtual Dom, old and new virtual Dom will compare the virtual Dom, if compared with the old between virtual new virtual Dom Dom and changed, the new virtual Dom will replace the old virtual Dom, At the same time, a new real Dom is generated on the page
Representation of the virtual Dom
const nodeDom = {
"sel": "div"."data": {
"class": { "box": true}},"children": [{"sel": "span"."data": {},
"text": "I am the word."
},
{
"sel": "ul"."data": {},
"children": [{"sel": "li"."data": {}, "text": The word "apple" },
{ "sel": "li"."data": {}, "text": "Banana" },
{ "sel": "li"."data": {}, "text": "Lemon"}]}]}Copy the code
If we insert a new message in ul at this point, the new virtual Dom will look like this:
const nodeDom = {
"sel": "div"."data": {
"class": { "box": true}},"children": [{"sel": "span"."data": {},
"text": "I am the word."
},
{
"sel": "ul"."data": {},
"children": [{"sel": "li"."data": {}, "text": The word "apple" },
{ "sel": "li"."data": {}, "text": "Banana" },
{ "sel": "li"."data": {}, "text": "Lemon" },
{ "sel": "li"."data": {}, "text": "Orange"},]}]}Copy the code
An important function of the virtual Dom: the H function
- The h function is used to generate a virtual node (Vnode)
- The h function is called like this
h('a', {props: {href:'https://www.baidu.com'}},"Baidu")
// The virtual node reached by calling h is
{ "sel": "a"."data": { "props": { "href": "https://www.baidu.com"}},"text": "Baidu" }
// The actual node of the page is:
<a href="https://www.baidu.com"> baidu < / a >//h functions can be nested
const myNode = h('ul',{},[
h('li', {},'apple'),
h('li', {},'banana'),
h('li', {},'lemon')])// Get the virtual Dom
{
'sel':'ul'.'data': {},'children':[
{'sel':'li'.data: {},'text':'apple'},
{'sel':'li'.data: {},'text':'banana'},
{'sel':'li'.data: {},'text':'lemon']}},// In this case, the virtual Dom needs to be uptree by patch function. Today, only h function and diff algorithm are handwritten
const box = document.getElementById('box')
patch(box, myNode)
Copy the code
To be continued