1.创建虚拟节点Vnode的函数 createVNode()
2.在render中创建虚拟节点VNodes
3.在createApp中把得到的虚拟节点挂载到根节点上去
首先是写一个创建虚拟dom的函数
function createVNode(tag,props,children)
{
return {tag,props,children}
}
然后在根组件中render函数中创建虚拟dom
return createVNode("div",{
id:"app-id",
class:"show"
},[createVNode('p',null,"heihei"),createVNode("p",null,"hh")])
然后在createApp函数中使用来自render返回的结果,将虚拟dom挂载
import { effect } from './reactivity/index.js'
import mountElement from './renderer/index.js'
export function createApp(rootComponent)
{
return {
mount(rootContainer)
{
const context=rootComponent.setup();
effect(()=>{
rootContainer.innerText="";
const subTree=rootComponent.render(context);
mountElement(subTree,rootContainer)
})
}
}
}
挂载函数mountElement
export default function mountElement(vnode,container)
{
const {tag,props,children}=vnode;
const element=document.createElement(tag);
if(props)
{
for(const key in props)
{
const value=props[key];
element.setAttribute(key,value);
}
}
if(typeof children ==="string")
{
const textNode=document.createTextNode(children);
element.append(textNode);
}
else if(Array.isArray(children))
{
children.forEach(vnode=>{
mountElement(vnode,element);
})
}
container.append(element);
}