真实dom
<ul id='list'>
<li class='item'>Item 1</li>
<li class='item'>Item 2</li>
<li class='item'>Item 3</li>
</ul>
虚拟dom
let el = new Element('ul', { id: 'list' }, [
new Element('li', { class: 'item' }, ['Item1']),
new Element('li', { class: 'item' }, ['Item2']),
new Element('li', { class: 'item' }, ['Item3']),
]);
构建连接类
class Element {
constructor(tagName, props, children) {
this.tagName = tagName;
this.props = props;
this.children = children;
}
render() { //渲染,递归
let el = document.createElement(this.tagName);
let props = this.props;
for (let propName in props) {
let propValue = props[propName];
el.setAttribute(propName, propValue);
}
let children = this.children || [];
children.forEach((child) => {
var childEl;
if (child instanceof Element) {
childEl = child.render();
} else {
childEl = document.createTextNode(child);
}
el.appendChild(childEl);
});
return el;
}
}
/**虚拟dom描述真实dom
<ul id='list'>
<li class='item'>Item 1</li>
<li class='item'>Item 2</li>
<li class='item'>Item 3</li>
</ul>
**/
let el = new Element('ul', { id: 'list' }, [
new Element('li', { class: 'item' }, ['Item1']),
new Element('li', { class: 'item' }, ['Item2']),
new Element('li', { class: 'item' }, ['Item3']),
]);
let ul = el.render();
document.body.appendChild(ul);