This article shares with you a summary of relevant knowledge points about Vue’s diff algorithm. Friends who are interested can refer to it.
Virtual dom
The diff algorithm must first clarify the concept that the object of diff is the virtual dom, and updating the real dom is the result of the diff algorithm
Vnode base class
constructor ( 。。。 ) { this.tag = tag this.data = data this.children = children this.text = text this.elm = elm this.ns = undefined this.context = context this.fnContext = undefined this.fnOptions = undefined this.fnScopeId = undefined this.key = data && data.key this.componentOptions = componentOptions this.componentInstance = undefined this.parent = undefined this.raw = false this.isStatic = false this.isRootInsert = true this.isComment = false this.isCloned = false this.isOnce = false this.asyncFactory = asyncFactory this.asyncMeta = undefined this.isAsyncPlaceholder = false }
This part of the code is mainly to better understand the meaning of the specific diff attributes in the diff algorithm, and of course to better understand the vnode instance
Overall process
The core function is the patch function
isUndef judgment (whether it is undefined or null)
// empty mount (likely as component), create new root elementcreateElm(vnode, insertedVnodeQueue) Here you can find that creating nodes is not inserted one by one, but put into a queue for unified batch processing
Core function sameVnode
function sameVnode (a, b) { return ( a.key === b.key && ( ( a.tag === b.tag && a.isComment === b.isComment && isDef(a.data) === isDef(b.data) && sameInputType(a, b) ) || ( isTrue(a.isAsyncPlaceholder) && a.asyncFactory === b.asyncFactory && isUndef(b.asyncFactory.error) ) ) ) }
Here is an outer comparison function that directly compares the key, tag (label), and data of two nodes ( Note that data here refers to VNodeData), and the type is directly compared for input.
export interface VNodeData { key?: string | number; slot?: string; scopedSlots?: { [key: string]: ScopedSlot }; ref?: string; tag?: string; staticClass?: string; class?: any; staticStyle?: { [key: string]: any }; style?: object[] | object; props?: { [key: string]: any }; attrs?: { [key: string]: any }; domProps?: { [key: string]: any }; hook?: { [key: string]: Function }; on?: { [key: string]: Function | Function[] }; nativeOn?: { [key: string]: Function | Function[] }; transition?: object; show?: boolean; inlineTemplate?: { render: Function; staticRenderFns: Function[]; }; directives?: VNodeDirective[]; keepAlive?: boolean; }
This will confirm whether the two nodes have further comparison value, otherwise they will be replaced directly
The replacement process is mainly a createElm function and the other is to destroy the oldVNode
// destroy old node if (isDef(parentElm)) { removeVnodes(parentElm, [oldVnode], 0, 0) } else if (isDef(oldVnode.tag)) { invokeDestroyHook(oldVnode) }
Insert To simplify the process, it is to determine the type of the node and call
createComponent respectively (it will determine whether there are children and then call it recursively)
createComment
createTextNode
After creation After using the insert function
, you need to use the hydrate function to map the virtual dom and the real dom
function insert (parent, elm, ref) { if (isDef(parent)) { if (isDef(ref)) { if (ref.parentNode === parent) { nodeOps.insertBefore(parent, elm, ref) } } else { nodeOps.appendChild(parent, elm) } } }
Core function
function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) { if (oldVnode === vnode) { return } const elm = vnode.elm = oldVnode.elm if (isTrue(oldVnode.isAsyncPlaceholder)) { if (isDef(vnode.asyncFactory.resolved)) { hydrate(oldVnode.elm, vnode, insertedVnodeQueue) } else { vnode.isAsyncPlaceholder = true } return } if (isTrue(vnode.isStatic) && isTrue(oldVnode.isStatic) && vnode.key === oldVnode.key && (isTrue(vnode.isCloned) || isTrue(vnode.isOnce)) ) { vnode.componentInstance = oldVnode.componentInstance return } let i const data = vnode.data if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) { i(oldVnode, vnode) } const oldCh = oldVnode.children const ch = vnode.children if (isDef(data) && isPatchable(vnode)) { for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode) if (isDef(i = data.hook) && isDef(i = i.update)) i(oldVnode, vnode) } if (isUndef(vnode.text)) { if (isDef(oldCh) && isDef(ch)) { if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly) } else if (isDef(ch)) { if (isDef(oldVnode.text)) nodeOps.setTextContent(elm, '') addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue) } else if (isDef(oldCh)) { removeVnodes(elm, oldCh, 0, oldCh.length - 1) } else if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, '') } } else if (oldVnode.text !== vnode.text) { nodeOps.setTextContent(elm, vnode.text) } if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.postpatch)) i(oldVnode, vnode) } }
const el = vnode.el = oldVnode.el This is a very important step, let vnode.el refer to the current real dom. When el is modified, vnode.el will change synchronously.
Compare whether the two references are consistent
I don’t know what asyncFactory does after that, so I can’t understand this comparison
Static node comparison key, no re-rendering will be done after the same, directly copy componentInstance (once command takes effect here)
If vnode is a text node or comment node , but when vnode.text != oldVnode.text, you only need to update the text content of vnode.elm
Comparison of children
If only oldVnode has child nodes, then delete these nodes
If only vnode has child nodes, then create these child nodes, here if oldVnode is a The text node sets the text of vnode.elm to the empty string
If both oldVnode and None of vnode has child nodes, but oldVnode is a text node or comment node, so set the text of vnode.elm to an empty string
- updateChildren
This part focuses on the entire algorithmFirst four pointers, oldStart, oldEnd, newStart, newEnd, two arrays, oldVnode, Vnode.
function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) { let oldStartIdx = 0 let newStartIdx = 0 let oldEndIdx = oldCh.length - 1 let oldStartVnode = oldCh[0] let oldEndVnode = oldCh[oldEndIdx] let newEndIdx = newCh.length - 1 let newStartVnode = newCh[0] let newEndVnode = newCh[newEndIdx] let oldKeyToIdx, idxInOld, vnodeToMove, refElm while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { if (isUndef(oldStartVnode)) { oldStartVnode = oldCh[++oldStartIdx] // Vnode has been moved left } else if (isUndef(oldEndVnode)) { oldEndVnode = oldCh[--oldEndIdx] } else if (sameVnode(oldStartVnode, newStartVnode)) { patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue) oldStartVnode = oldCh[++oldStartIdx] newStartVnode = newCh[++newStartIdx] } else if (sameVnode(oldEndVnode, newEndVnode)) { patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue) oldEndVnode = oldCh[--oldEndIdx] newEndVnode = newCh[--newEndIdx] } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue) canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm)) oldStartVnode = oldCh[++oldStartIdx] newEndVnode = newCh[--newEndIdx] } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue) canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm) oldEndVnode = oldCh[--oldEndIdx] newStartVnode = newCh[++newStartIdx] } else { if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx) idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx) if (isUndef(idxInOld)) { // New element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx) } else { vnodeToMove = oldCh[idxInOld] if (sameVnode(vnodeToMove, newStartVnode)) { patchVnode(vnodeToMove, newStartVnode, insertedVnodeQueue) oldCh[idxInOld] = undefined canMove && nodeOps.insertBefore(parentElm, vnodeToMove.elm, oldStartVnode.elm) } else { // same key but different element. treat as new element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx) } } newStartVnode = newCh[++newStartIdx] } } if (oldStartIdx > oldEndIdx) { refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue) } else if (newStartIdx > newEndIdx) { removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx) } }
Several situations and processing of a loop comparison (the following - all refer to index -) The comparison is the node node of the comparison. The abbreviation is not rigorous and the comparison uses the sameVnode function, which is not true. Congruent
Conditions for the entire loop not to end oldStartIdx
##oldStart === newStart, oldStart newStart- oldEnd === newEnd, oldEnd-- newEnd--
- oldStart === newEnd, oldStart Insert to the end of the queue oldStart newEnd--
- oldEnd === newStart, oldEnd is inserted into the beginning of the queue oldEnd-- newStart
- This is the only way to handle all the remaining situations. This kind of processing, after processing newStart
- newStart finds the same one in old, then move this to the front of oldStart
- If you don't find the same one, create one and put it before oldStart
- It is not completed after the loop endsThere is still a period of judgment before it is complete
if (oldStartIdx > oldEndIdx) { refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue) } else if (newStartIdx > newEndIdx) { removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx) }Simple What I mean is that after the loop ends, look at the contents between the four pointers, in the old array and in the new array, just back out more and make up less. The above is what I compiled for everyone. I hope it will be helpful to everyone in the future. Related articles:
Angular5 method of adding style class to the label of the component itself
vue-cli development environment to implement cross-domain requests Method
Detailed explanation of Vue-cli webpack mobile terminal automatic build rem problem
The above is the detailed content of Summary of vue's diff algorithm knowledge points. For more information, please follow other related articles on the PHP Chinese website!

Python作为当下最大众化的编程语言,相信每天都会有大量的新手朋友进入学习大军的行列。但是无论一门语言是多么的容易学习,其基本概念、基础知识还是比较多的,对于小白来说,一时间要掌握这么多还是有些吃力。今天精选收集了众多Python相关的知识速查表,可以说是包罗万象,以后妈妈再也不用担心大家记不住任何知识点了!Python基础Pythonbasics该速查表包含了所有的Python基本知识,从变量数据类型到列表字符串,从环境安装到常用库的使用,可以说面面俱到。Beginner'sPytho

Linux下system()函数的总结在Linux系统中,system()函数是一个非常常用的函数,它可以用于执行命令行命令。本文将对system()函数进行详细的介绍,并提供一些具体的代码示例。一、system()函数的基本用法system()函数的声明如下:intsystem(constchar*command);其中,command参数是一个字符

在linux下,直接使用svndiff命令查看代码的修改是很吃力的,于是在网上搜索到了一个比较好的解决方案,就是让vimdiff作为svndiff的查看代码工具,尤其对于习惯用vim的人来说真的是很方便。当使用svndiff命令比较某个文件的修改前后时,例如执行以下命令:$svndiff-r4420ngx_http_limit_req_module.c那么实际会向默认的diff程序发送如下命令:-u-Lngx_http_limit_req_module.c(revision4420)-Lngx_

HTML缓存机制大揭秘:必备的知识点,需要具体代码示例在Web开发中,性能一直是一个重要的考量因素。而HTML缓存机制是提升Web页面性能的关键之一。本文将揭秘HTML缓存机制的原理和实践技巧,并提供具体的代码示例。一、HTML缓存机制的原理Web页面访问过程中,浏览器通过HTTP协议请求服务器获取HTML页面。HTML缓存机制就是将HTML页面缓存在浏览器

MySQL是世界上最流行的关系型数据库管理系统之一,因其可靠性、高安全性、高扩展性以及相对低的成本而得到了广泛应用。MySQL的数据类型定义了各种数据类型的存储方式,是MySQL的重要组成部分。本文将详解MySQL的数据类型,以及在实际应用中需要注意的一些知识点。一、MySQL的数据类型分类MySQL的数据类型可以分为以下几类:整数类型:包括TINYINT、

Git工作流程管理经验总结引言:在软件开发中,版本管理是一个非常重要的环节。而Git作为目前最流行的版本管理工具之一,其强大的分支管理能力使得团队协作更加高效灵活。本文将就Git工作流程管理经验进行总结和分享。一、Git工作流程简介Git支持多种工作流程,可以根据团队的实际情况选择合适的工作流程。常见的Git工作流程有集中式工作流、功能分支工作流、GitF

Oracle数据类型大揭秘:你必须了解的知识点,需要具体代码示例Oracle作为世界领先的数据库管理系统之一,在数据存储和处理中扮演着重要的角色。在Oracle中,数据类型是非常重要的概念,它定义了数据在数据库中的存储格式、范围和操作方式。本文将揭示Oracle数据类型的各种知识点,并且通过具体的代码示例展示它们的用法和特点。一、常见的数据类型字符型数据类型

随着机器学习和量子计算的巨大进步,我们现在有了更强大的新工具,能够以新的方式与各行业研究者合作,并从根本上加速突破性科学发现的进展。 本期谷歌年终总结的主题是「自然科学」,文章作者为谷歌研究院的杰出科学家John Platt,1989年博士毕业于加州理工大学。自从八年前加入 Google Research 以来,我有幸成为一个天才研究人员的社区的一员,致力于应用前沿计算技术来推动应用科学的可能性,目前团队正在探索物理和自然科学的课题,从帮助组织全世界的蛋白质和基因组信息以造福人们的生活,到利用量


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
