首页 > web前端 > js教程 > 正文

从头开始设计虚拟 DOM:分步指南

Mary-Kate Olsen
发布: 2024-10-20 20:38:30
原创
277 人浏览过

Designing a Virtual DOM from Scratch: A Step-by-Step Guide

如果您听说过 React 或 Vue 等前端库,您可能遇到过术语 虚拟 DOM。虚拟 DOM 是一个聪明的概念,它可以通过提高 DOM 更新效率来帮助加快 Web 开发速度。

在本指南中,我们将详细介绍如何使用通用的类似代码的步骤从头开始实现简单的虚拟 DOM。

什么是虚拟 DOM?

虚拟 DOM 只是真实 DOM(网页结构)的轻量级内存中表示。我们不是直接更新真实 DOM(这很慢),而是首先对虚拟 DOM 进行更改,弄清楚发生了什么变化,然后只更新真实 DOM 中需要更新的部分。这可以节省时间并使您的应用程序运行得更快!


第 1 步:将虚拟 DOM 表示为树

将网页的结构想象成一棵树,其中每个元素(如

)都是树中的一个“节点”。 虚拟 DOM 节点 是一个代表这些元素之一的小对象。

这是一个例子:

Virtual DOM Node:
{
  type: 'div',
  props: { id: 'container' },  // attributes like id, class, etc.
  children: [                 // children inside this element
    {
      type: 'p',              // a <p> tag (paragraph)
      props: {},
      children: ['Hello, world!']  // text inside the <p> tag
    }
  ]
}
登录后复制
登录后复制

这描述了一个

;带有 id="container" 的元素,其中包含

;带有文本 “你好,世界!”.

的元素

要点:

  • 每个节点都有一个类型(例如 div、p)。
  • 它可以有 props(如 id、class 等)。
  • 它还有可以是其他元素或文本的子元素。

第二步:将虚拟 DOM 渲染到真实 DOM

现在我们有了虚拟 DOM,我们需要一种方法将其转换为页面上的真实 HTML。

让我们编写一个名为 render 的函数,它接收虚拟 DOM 节点并将其转换为实际的 HTML 元素。

function render(vNode) {
  // 1. Create a real element based on the Virtual DOM type (e.g., div, p).
  const element = document.createElement(vNode.type);

  // 2. Apply any attributes (props) like id, class, etc.
  for (const [key, value] of Object.entries(vNode.props)) {
    element.setAttribute(key, value);
  }

  // 3. Process the children of this Virtual DOM node.
  vNode.children.forEach(child => {
    if (typeof child === 'string') {
      // If the child is just text, create a text node.
      element.appendChild(document.createTextNode(child));
    } else {
      // If the child is another Virtual DOM node, recursively render it.
      element.appendChild(render(child));
    }
  });

  return element;  // Return the real DOM element.
}
登录后复制
登录后复制

这里发生了什么?

  • 我们创建一个元素 (document.createElement(vNode.type))。
  • 我们添加任何属性(如 id、class 等)。
  • 我们通过添加文本或在每个子元素上再次调用渲染来处理子元素(文本或其他元素)。

第 3 步:比较(差异)新旧虚拟 DOM

当我们的网络应用程序发生某些变化(例如文本或元素的样式)时,我们会创建一个新的虚拟 DOM。但在更新真实 DOM 之前,我们需要比较旧 Virtual DOM新 Virtual DOM 来找出发生了什么变化。这称为“比较”

让我们创建一个比较两个虚拟 DOM 的函数:

Virtual DOM Node:
{
  type: 'div',
  props: { id: 'container' },  // attributes like id, class, etc.
  children: [                 // children inside this element
    {
      type: 'p',              // a <p> tag (paragraph)
      props: {},
      children: ['Hello, world!']  // text inside the <p> tag
    }
  ]
}
登录后复制
登录后复制

差异如何工作:

  • 节点类型更改:如果元素类型发生更改(例如将
    更改为

    ),我们会将其标记为替换。

  • 文本更改:如果内部文本发生更改,我们会更新文本。
  • 属性和子元素:我们检查元素的任何属性(props)或子元素是否已更改。

  • 第 4 步:修补真实 DOM

    一旦我们知道发生了什么变化,我们就需要将这些更改应用到真实的 DOM 上。我们将此过程称为修补

    修补功能的外观如下:

    function render(vNode) {
      // 1. Create a real element based on the Virtual DOM type (e.g., div, p).
      const element = document.createElement(vNode.type);
    
      // 2. Apply any attributes (props) like id, class, etc.
      for (const [key, value] of Object.entries(vNode.props)) {
        element.setAttribute(key, value);
      }
    
      // 3. Process the children of this Virtual DOM node.
      vNode.children.forEach(child => {
        if (typeof child === 'string') {
          // If the child is just text, create a text node.
          element.appendChild(document.createTextNode(child));
        } else {
          // If the child is another Virtual DOM node, recursively render it.
          element.appendChild(render(child));
        }
      });
    
      return element;  // Return the real DOM element.
    }
    
    登录后复制
    登录后复制

    关键操作:

    • 替换: 将一个元素完全替换为另一个元素。
    • 文本:更新元素内的文本。
    • 更新:根据更改更新属性和子项。

    虚拟 DOM 流程总结:

    1. 虚拟 DOM 树: 我们创建一个树状结构,表示网页上的元素及其层次结构。
    2. 渲染为真实 DOM: 此虚拟 DOM 被转换为真实的 HTML 元素并放置在页面上。
    3. 比较算法:当发生变化时,我们将旧的 Virtual DOM 与新的进行比较以找出差异。
    4. 修补真实 DOM: 以最有效的方式将这些更改应用到真实 DOM。

    最后的想法

    虚拟 DOM 是一个强大的工具,它通过减少对真实 DOM 的不必要的更改来更快地更新用户界面。通过实现虚拟 DOM,我们可以优化 Web 应用程序更新和渲染元素的方式,从而带来更快、更流畅的用户体验。

    这是虚拟 DOM 概念的基本实现,但您现在已经有了理解 React 等框架如何使用它的基础!

以上是从头开始设计虚拟 DOM:分步指南的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门推荐
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!