FE-Interview icon indicating copy to clipboard operation
FE-Interview copied to clipboard

Day159:如何把真实 dom 转变为虚拟 dom,代码实现一下

Open Genzhen opened this issue 5 years ago • 1 comments

每日一题会在下午四点在交流群集中讨论,五点小程序中更新答案 二维码加载失败可点击 小程序二维码

扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。

Genzhen avatar Oct 19 '20 07:10 Genzhen

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);
}

18232751914 avatar Mar 30 '23 07:03 18232751914