【vue】什么是虚拟Dom,怎么实现虚拟DOM,虚拟DOM一定更快吗

2024-02-28 14:44

本文主要是介绍【vue】什么是虚拟Dom,怎么实现虚拟DOM,虚拟DOM一定更快吗,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

什么是虚拟Dom

虚拟 DOM 基于虚拟节点 VNode,VNode 本质上是一个对象,VDOM 就是VNode 组成的

        废话,js 中所有的东西都是对象

虚拟DOM 为什么快,做了哪些优化

  1. 批量更新
    1. 多个DOM合并更新
    2. 减少浏览器的重排和重绘
  2. 局部更新
    1. 通过新VDOM对比,diff 算法
    2. 只更新需要重新渲染的真实 DOM
    3. 减少开销
  3. 跨平台支持
    1. node、浏览器、移动端、小程序都可以支持

虚拟DOM一定更快吗,不一定

  1. 额外的内存占用
    1. 虚拟DOM需要维护一个表示整个组件树的数据结构,这可能会占用额外的内存。
  2. VDOM 生成、对比,渲染都有额外的开销
  3. VDOM 适合中大型项目
  4. 简单的程序不适合VDOM,直接操作真实DOM更好
  5. 有些框架不用VDOM也很快
    1. 使用异步渲染技术
      1. requestAnimationFrame
      2. MutationObserver

实现VDOM

vue3 源码 runtime-core/src/vnode.ts 有关于 VNode 的定义

export interface VNode<HostNode = RendererNode,HostElement = RendererElement,ExtraProps = { [key: string]: any },
> {/*** @internal*/__v_isVNode: true/*** @internal*/[ReactiveFlags.SKIP]: truetype: VNodeTypesprops: (VNodeProps & ExtraProps) | nullkey: string | number | symbol | nullref: VNodeNormalizedRef | null/*** SFC only. This is assigned on vnode creation using currentScopeId* which is set alongside currentRenderingInstance.*/scopeId: string | null/*** SFC only. This is assigned to:* - Slot fragment vnodes with :slotted SFC styles.* - Component vnodes (during patch/hydration) so that its root node can*   inherit the component's slotScopeIds* @internal*/slotScopeIds: string[] | nullchildren: VNodeNormalizedChildrencomponent: ComponentInternalInstance | nulldirs: DirectiveBinding[] | nulltransition: TransitionHooks<HostElement> | null// DOMel: HostNode | nullanchor: HostNode | null // fragment anchortarget: HostElement | null // teleport targettargetAnchor: HostNode | null // teleport target anchor/*** number of elements contained in a static vnode* @internal*/staticCount: number// suspensesuspense: SuspenseBoundary | null/*** @internal*/ssContent: VNode | null/*** @internal*/ssFallback: VNode | null// optimization onlyshapeFlag: numberpatchFlag: number/*** @internal*/dynamicProps: string[] | null/*** @internal*/dynamicChildren: VNode[] | null// application root node onlyappContext: AppContext | null/*** @internal lexical scope owner instance*/ctx: ComponentInternalInstance | null/*** @internal attached by v-memo*/memo?: any[]/*** @internal __COMPAT__ only*/isCompatRoot?: true/*** @internal custom element interception hook*/ce?: (instance: ComponentInternalInstance) => void
}

使用 createVNode 创建虚拟节点  

虚拟 dom 就是虚拟 node 节点的结合,每个 Vnode 都有一个 children 属性,children 的每个元素也是一个 VNode,他们有共同的根节点,就形成了一个虚拟的树结构。

自己实现虚拟 DOM 的重点步骤

  1. 定义一个 VNode 数据结构【这个如果是用 js,没有接口类型定义,就不用在代码中直接体现】
    1. 类中有 children 属性【用来存储子节点】
    2. 有 tag 代表标签【用来存储真实 html 的标签, div, p, span 等】
    3. 有 props 节点的属性【用来存储 html 元素的各种属性,style, class 等】
  2. 定义一个创建 VNode 的函数或类【createVNode】
  3. 定义一个渲染函数,将 VDOM 转成真实节点【render】

下面是我根据上面的步骤自己实现的:

// 创建虚拟节点函数
function createVNode(tag, props, children) {// 虚拟节点必须包含的三个属性return {isVnode: true, // 用来判断是否是虚拟节点,也不可不用这个tag,props,children // 数组}
}function render(VNode) {const { tag, props, children } = VNode// 创建真实 Dom 元素const element = document.createElement(tag)// 给 dom 元素增加属性for(let key in props) {element.setAttribute(key, props[key])}for(let i =0; i < children.length; i ++) {let child = children[i]// 如果子节点还是虚拟节点,就递归调用渲染函数if (child.isVnode ) {element.appendChild(render(child))} else {// 最终的真实节点element.appendChild(document.createTextNode(child))}}return element
}const vDom = createVNode('div', {style: 'color:red'}, [createVNode('h1', { style: 'color:blue'}, ['你好']),createVNode('p', {}, ['再见'])
])const realDom = render(vDom)
console.log(realDom)

 复制上面代码到浏览器开发者工具中可以直接运行

下面 chatgpt 给的答案,使用了一个 vnode类,看起来更好一些:

// 定义虚拟DOM节点的数据结构
class VNode {constructor(tag, props, children) {this.tag = tag;this.props = props;this.children = children;}// 渲染虚拟DOM为真实DOMrender() {const element = document.createElement(this.tag);// 设置属性for (const key in this.props) {element.setAttribute(key, this.props[key]);}// 渲染子节点this.children.forEach(child => {if (child instanceof VNode) {element.appendChild(child.render());} else {element.appendChild(document.createTextNode(child));}});return element;}
}// 创建虚拟DOM
const virtualDOM = new VNode('div', { class: 'container' }, [new VNode('h1', {}, ['Hello, Virtual DOM!']),new VNode('p', {}, ['This is a paragraph.']),
]);// 将虚拟DOM渲染到页面中
const root = document.getElementById('root');
root.appendChild(virtualDOM.render());

这篇关于【vue】什么是虚拟Dom,怎么实现虚拟DOM,虚拟DOM一定更快吗的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/755799

相关文章

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

Spring Security自定义身份认证的实现方法

《SpringSecurity自定义身份认证的实现方法》:本文主要介绍SpringSecurity自定义身份认证的实现方法,下面对SpringSecurity的这三种自定义身份认证进行详细讲解,... 目录1.内存身份认证(1)创建配置类(2)验证内存身份认证2.JDBC身份认证(1)数据准备 (2)配置依

利用python实现对excel文件进行加密

《利用python实现对excel文件进行加密》由于文件内容的私密性,需要对Excel文件进行加密,保护文件以免给第三方看到,本文将以Python语言为例,和大家讲讲如何对Excel文件进行加密,感兴... 目录前言方法一:使用pywin32库(仅限Windows)方法二:使用msoffcrypto-too

C#使用StackExchange.Redis实现分布式锁的两种方式介绍

《C#使用StackExchange.Redis实现分布式锁的两种方式介绍》分布式锁在集群的架构中发挥着重要的作用,:本文主要介绍C#使用StackExchange.Redis实现分布式锁的... 目录自定义分布式锁获取锁释放锁自动续期StackExchange.Redis分布式锁获取锁释放锁自动续期分布式

springboot使用Scheduling实现动态增删启停定时任务教程

《springboot使用Scheduling实现动态增删启停定时任务教程》:本文主要介绍springboot使用Scheduling实现动态增删启停定时任务教程,具有很好的参考价值,希望对大家有... 目录1、配置定时任务需要的线程池2、创建ScheduledFuture的包装类3、注册定时任务,增加、删