vertualDom --虚拟dom
2019-12-11 本文已影响0人
田成力
class Element {
constructor(type, props, children) {
this.type = type;
this.props = props;
this.children = children;
}
}
//设置属性
function setAttr(node, key, value) {
switch (key) {
case 'value':
if (node.tagName.toUpperCase() === 'INPUT' || node.tagName.toUpperCase() === 'TEXTAREA') {
node.value = value;
} else {
node.setAttribute(key, value);
}
break;
case 'style':
node.style.cssText = value;
break;
default:
node.setAttribute(key, value);
break;
}
}
//返回虚拟节点
function createElement(type, props, children) {
return new Element(type, props, children);
}
//将虚拟dom转换为真实dom
function render(eleObj) {
let el = document.createElement(eleObj.type);
for (let key in eleObj.props) {
setAttr(el, key, eleObj.props[key]);
}
//遍历儿子节点,如果屎虚拟dom继续渲染,不是的话就是文本节点
eleObj.children.forEach((children) => {
child = (child instanceof Element) ? render(child) : document.createTextNode(child);
el.appendChild(child);
})
return el;
}
//将元素插入到页面中
function renderDom(el, target) {
target.appendChild(el)
}
let vertualDom = createElement('ul', { class: 'list' }, [
createElement('li', { class: 'item' }, ['a']),
createElement('li', { class: 'item' }, ['b']),
createElement('li', { class: 'item' }, ['c']),
]);
let el = render(vertualDom);
renderDom(el, window.root);
console.log(vertualDom);