FE-Interview
FE-Interview copied to clipboard
Day159:如何把真实 dom 转变为虚拟 dom,代码实现一下
class VNode {
constructor(tagName, attrs, children) {
this.tagName = tagName; // 标签名
this.attrs = attrs; // 属性对象
this.children = children; // 子节点列表
}
}
// 将真实 DOM 转换为虚拟 DOM
function toVNode(node) {
// 如果是文本节点,则直接返回文本内容
if (node.nodeType === Node.TEXT_NODE) {
return node.textContent;
}
// 否则创建一个虚拟 DOM 节点对象
const tagName = node.tagName.toLowerCase(); // 标签名
const attrs = {}; // 属性对象
for (let i = 0; i < node.attributes.length; i++) {
const attr = node.attributes[i];
attrs[attr.name] = attr.value;
}
const children = []; // 子节点列表
for (let i = 0; i < node.childNodes.length; i++) {
const childNode = node.childNodes[i];
children.push(toVNode(childNode));
}
return new VNode(tagName, attrs, children);
}