vue中的虚拟dom转化为真实dom

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")])
//这样返回的是一颗虚拟的dom树

然后在createApp函数中使用来自render返回的结果,将虚拟dom挂载

///这里需要引入把虚拟节点转换成为真是节点的函数mountElement
import { effect } from './reactivity/index.js'
import mountElement from './renderer/index.js'
export function createApp(rootComponent)
{
    return {
        //调用createApp方法返回一个mount对象
        mount(rootContainer)
        {
            //组件进入的时候调用组件的setup函数拿到组件的
            //一些依赖的值
            const context=rootComponent.setup();
            //然后执行effect函数进行第一次渲染和依赖的收集工作
            effect(()=>{
                rootContainer.innerText="";
                const subTree=rootComponent.render(context);
                mountElement(subTree,rootContainer)
            })
        }
    }
}

挂载函数mountElement

export default function mountElement(vnode,container)
{
    //vnode->tag,props,children

    //tag
    const {tag,props,children}=vnode;
    const element=document.createElement(tag);

    //props
    if(props)
    {
        //一个element可能有很多的prop,需要遍历
        for(const key in props)
        {
            const value=props[key];
            element.setAttribute(key,value);
        }
    }

    //children->可以字符串和 数组类型的children
    if(typeof children ==="string")
    {
        const textNode=document.createTextNode(children);
        element.append(textNode);
    }
    //children是一个数组
    else if(Array.isArray(children))
    {
        children.forEach(vnode=>{
            //在当前的element容器中递归调用‘
            //并且挂载到当前的容器上去
            mountElement(vnode,element);
        })
    }
    container.append(element);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值