简体   繁体   English

Virtual DOM 如何在 React 或 Vue 中工作

[英]How Virtual DOM works in React or Vue

I ma student and I m trying to create own Virtual DOM for my college project ( It will not have any advanced feature like props or events, I will keep it simple ) in JavaScript like other famous frameworks React, Vue and other.我是学生,我正在尝试在 JavaScript 中为我的大学项目创建自己的虚拟 DOM(它不会有任何高级功能,如道具或事件,我会保持简单),就像其他著名的框架 React、Vue 等一样。

I just want to know that when we have multiple file of code( code splitting ).我只想知道当我们有多个代码文件(代码拆分)时。 If I make a change in any deep child than do I need to compare complete virtual DOM (including all child and parent element) or I just need to compare only that child elements.如果我对任何深层子元素进行更改,我不需要比较完整的虚拟 DOM(包括所有子元素和父元素),或者我只需要比较那个子元素。

If I have to compare complete new virtual DOM ( including all children ) with previous Virtual DOM.如果我必须将完整的新虚拟 DOM(包括所有子项)与以前的虚拟 DOM 进行比较。 Then Why should I care re-rendering in React or Vue ( because any changes in child will force the framework to compare complete Virtual DOM )那我为什么要关心在 React 或 Vue 中重新渲染(因为 child 的任何更改都会迫使框架比较完整的 Virtual DOM)

Answer to your last point as I infer from my experience of React is that comparing Virtual DOM's in Javascript is the thing that helps react know what things it has to re-render on the actual DOM, So the "re-rendering" is the hard part on which the performance of the APP takes the hit.根据我对 React 的经验推断,对你最后一点的回答是,比较 Javascript 中的虚拟 DOM 有助于反应知道它必须在实际 DOM 上重新渲染什么,所以“重新渲染”很难APP性能受到影响的部分。 Hopefully, this would help.希望这会有所帮助。

For Vue, The working of virtual DOM differs in vue2 and vue3.对于 Vue,虚拟 DOM 的工作方式在 vue2 和 vue3 中有所不同。

The way vue3 does it, is, vue3 的做法是,

  1. By parsing the HTML template or render function from the component files and converting it to a Virtual Node representation.通过解析 HTML 模板或从组件文件中渲染 function 并将其转换为虚拟节点表示。
  2. While doing the parsing, it records the nodes that have a dependency on dynamic data.在进行解析时,它会记录对动态数据具有依赖性的节点。
  3. Something like below像下面的东西
dynamicData = { data1: [ effect1, effect2, ... ], data2: [ effect4, effect5, ... ], ... }
  1. Effects are functions that define computations required to resolve certain data values.效果是定义解析某些数据值所需的计算的函数。
  2. Effects also include render function for the Virtual nodes效果还包括为虚拟节点渲染 function
  3. Render functions smartly converts virtual nodes to DOM elements渲染函数巧妙地将虚拟节点转换为 DOM 元素
  4. Now whenever data1 changes Vue3 re-executes the corresponding effects and triggers update for subsequent data changes.现在,每当 data1 更改时,Vue3 都会重新执行相应的效果并触发更新以进行后续数据更改。

References:参考:

  1. Vue3 Reactivity Vue3 反应性
  2. Vnode Transformation Vnode 转换

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM