1. 构建虚拟DOM,参考资料:https://juejin.cn/post/6844903806132568072#heading-2【仅做为个人学习笔记,如有侵权,请联系本人】
type: 指定元素的标签类型,如'li', 'div', 'a'等
props: 表示指定元素身上的属性,如class, style, 自定义属性等
children: 表示指定元素是否有子节点,参数以数组的形式传入
element.js 文件代码:
/* virtualDOM 基本结构 */ class element { constructor(type, props, children) { this.type = type; this.props = props; this.children = children; } }
/* 创建虚拟DOM元素 */ function createElement(type, props, children) { return new element(type, props, children); }
/* 将虚拟DOM渲染为真实DOM,并返回元素 */ function render(dom_object) { let el = document.createElement(dom_object.type); for (let key in dom_object.props) { setAttr(el, key, dom_object.props[key]); } dom_object.children.forEach(child => { child = (child instanceof element) ? render(child) : document.createTextNode(child); /* createTextNode 创建文本节点 */ el.appendChild(child); }); return el; }
/* 为el设置属性,可不可以直接node.setAttribute(key, value)? */ function setAttr(node, key, value) { if (key === 'value') { if (node.tagName.toLocaleLowerCase() === 'input' || node.tagName.toLocaleLowerCase() === 'textarea') { node.value = value; } else { node.setAttribute(key, value); } } else if (key === 'style') { node.style.cssText = value; } else { node.setAttribute(key, value); } }
function renderDOM(el, target) { target.appendChild(el); }
index.js 文件代码:
/** * index.js 程序入口 */ let box = document.querySelector('.box'); let virtualdom = createElement('ul', {class: 'list'}, [ createElement('li', {class: 'item'}, ['周杰伦']), createElement('li', {class: 'item'}, ['林俊杰']), createElement('li', {class: 'item'}, ['王力宏']) ]); console.log(virtualdom); // 打印查看虚拟DOM结构 renderDOM(render(virtualdom), box); // 将虚拟DOM转化为真实DOM
index.html 代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <div class="box"></div> <script src="element.js"></script> <script src="index.js"></script> </body> </html>