仿写简单的vue虚拟dom

最近在学vue 所以仿写了一些render函数的虚拟dom,还是挺有意思的:)
        function createElement(tag, prop, children) {
            if (!(this instanceof createElement)) {
                return new createElement(tag, prop, children)
            }
            if (Object.prototype.toString.call(prop) === "[object Array]") {
                children = prop;
                prop = {};
            }
            this.tag = tag;
            this.prop = prop;
            this.children = children;
            var count = 0;
            this.children.forEach(function(item) {
                if (item instanceof createElement) {
                    count += item.count;
                }
                count++;
            })
            this.count = count;
        }
        createElement.prototype.render = function() {
            var tag = this.tag;
            var prop = this.prop;
            var children = this.children;
            var dom = document.createElement(tag);
            for (item in prop) {
                dom.setAttribute(item, prop[item]);
            }
            children.forEach(function(child) {
                if (child instanceof createElement) {
                    var childDom = child.render();
                } else {
                    var childDom = document.createTextNode(child);
                }
                dom.appendChild(childDom);
            })
            return dom;
        }

以上为代码片

测试节点如下

        var dom = createElement("div", {
            class: "demo"
        }, ["you are", createElement("p", {
            id: "lala"
        }, ["gorgeous"])]);

        console.log(dom.render());

得出结果
图片

原文地址:博客内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值