// 将虚拟 DOM 渲染成真实 DOM
functionrender(vNode){if("string"===vNode.tag){returndocument.createTextNode(vNode.text)}constelement=document.createElement(vNode.tag)constchildren=vNode.childrenif(!children||children.length==0){returnelement}children.forEach(child=>{if(child.tag==='string'){element.appendChild(document.createTextNode(child.text));}else{element.appendChild(render(child));}})returnelement}
挂载虚拟 DOM
// 挂载点
constcontainer=document.getElementById('app');// 创建虚拟节点
constappNode=createElementVNode("div")constchildNode1=createTextVNode("Hello ")constchildNode2=createElementVNode("b",{},[createTextVNode("World")])appNode.children.push(childNode1,childNode2)// 将虚拟节点渲染真实 DOM
constrealDom=render(appNode)container.appendChild(realDOM);