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

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

如果您听说过 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 

tag (paragraph) props: {}, children: ['hello, world!'] // text inside the

tag } ]}

这描述了一个 id=”container” 的

元素,其中包含一个带有文本 “hello, world!”. 的

元素。

要点:

每个节点都有一个类型(例如 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 };}

差异如何工作:

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

更改为

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

文本更改:如果内部文本发生更改,我们会更新文本。属性和子元素:我们检查元素的任何属性(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 流程总结:

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

最后的想法

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

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

以上就是从头开始设计虚拟 DOM:分步指南的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1493484.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
在选择元素中动态创建选项
上一篇 2025年12月19日 15:43:32
如何在任何 Nextjs 应用程序中处理 Cookie 同意
下一篇 2025年12月19日 15:43:48

相关推荐

发表回复

登录后才能评论
关注微信