简易实现virtual-dom

const vnode = {
    tag: 'DIV',
    attrs: {
        id: 'app'
    },
    children: [{
            tag: 'SPAN',
            children: [{
                tag: 'A',
                children: []
            }]
        },
        {
            tag: 'SPAN',
            children: [{
                    tag: 'A',
                    children: []
                },
                {
                    tag: 'A',
                    children: []
                }
            ]
        }
    ]
}

function render(vnode) {
    if (typeof vnode === 'number') {
        vnode = String(vnode)
    }

    if (typeof vnode === 'string') {
        return document.createTextNode(vnode);
    }

    const element = document.createElement(vnode.tag);

    if (vnode.attrs) {
        Object.keys(vnode.attrs).forEach(attrKey => {
            element.setAttribute(key, vnode.attrs[attrKey]);
        })
    }

    if (vnode.children) {
        vnode.children.forEach((childNode) => {
            element.appendChild(render(childNode))
        })
    }

    return element;

}

 

posted @ 2021-11-23 16:18  LeoX的爬坑笔记  阅读(44)  评论(0编辑  收藏  举报