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

时间:2024-10-21

浏览:224

作者:佚名

大家好,今天本人给大家带来文章《从头开始设计虚拟 DOM:分步指南》,文中内容主要涉及到,如果你对文章方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

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

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

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

什么是虚拟 dom?

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


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

将网页的结构想象成一棵树,其中每个元素(如 <div>、<p> 或 <h1>)都是树中的一个“节点”。 虚拟 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> 元素,其中包含一个带有文本 “hello, world!”.

的 <p> 元素。

要点:

  • 每个节点都有一个类型(例如 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 的函数:

function diff(oldvnode, newvnode) {
  // if the node type has changed (e.g., from 'div' to 'p'), replace the node.
  if (oldvnode.type !== newvnode.type) {
    return { type: 'replace', newvnode };
  }

  // if the text inside has changed, we need to update the text.
  if (typeof oldvnode === 'string' && oldvnode !== newvnode) {
    return { type: 'text', newvnode };
  }

  // compare the properties (like id, class, etc.).
  const proppatches = diffprops(oldvnode.props, newvnode.props);

  // compare the children.
  const childpatches = diffchildren(oldvnode.children, newvnode.children);

  return { type: 'update', proppatches, childpatches };
}

差异如何工作:

  • 节点类型更改:如果元素类型发生更改(例如将 <div> 更改为 <p>),我们将其标记为替换。
  • 文本更改:如果内部文本发生更改,我们会更新文本。
  • 属性和子元素:我们检查元素的任何属性(props)或子元素是否已更改。

第 4 步:修补真实 dom

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

修补功能的外观如下:

function patch(parent, patches, index = 0) {
  if (!patches) return;  // If there are no changes, do nothing.

  const element = parent.childNodes[index];  // The element we’re patching.

  switch (patches.type) {
    case 'REPLACE':
      // Replace the old element with a new one.
      parent.replaceChild(render(patches.newVNode), element);
      break;

    case 'TEXT':
      // Update the text content of the element.
      element.textContent = patches.newVNode;
      break;

    case 'UPDATE':
      // Update the element’s properties and children.
      patchProps(element, patches.propPatches);
      patches.childPatches.forEach((childPatch, i) => patch(element, childPatch, i));
      break;
  }
}

关键操作:

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

虚拟 dom 流程总结:

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

最后的想法

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

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

今天关于《从头开始设计虚拟 DOM:分步指南》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

近期热门

更多

站内热门

更多

最新文章

更多

热门专题

更多
首页