简单模拟Vue虚拟DOM
<script>
function vElement(tageName, prop, children) {
if(!(this instanceof vElement)) {
return new vElement(tageName, prop, children)
}
if(Object.prototype.toString.call(prop) === "[object Array]") {
children = prop;
prop = {}
}
this.tageName = tageName;
this.children = children;
this.prop = prop;
var count = 0;
this.children.forEach(function(child, index) {
if(child instanceof vElement) {
count += child.count;
}
count++
})
this.count = count;
}
vElement.prototype.render = function() {
var el = document.createElement(this.tageName);
var children = this.children;
var prop = this.prop;
for(var item in prop) {
var curProp = prop[item];
el.setAttribute(item, curProp);
}
children.forEach(function(child, index) {
if(child instanceof vElement) {
var childDom = child.render();
}else{
var childDom = document.createTextNode(child)
}
el.appendChild(childDom)
})
return el;
}
var dom = vElement("div", {class:"demo", id:"demo1"}, ["hello world", vElement("p", {class:"demo2"},["我是p标签"])]);
console.log(dom)
console.log(dom.render());
</script>