Home > Article > Web Front-end > How to use the diff algorithm in vue
This time I will show you how to use the diff algorithm in vue, and what are the precautions for using the diff algorithm in vue. The following is a practical case, let's take a look.
1. When the data changes, how does vue update the node?
You must know that the cost of rendering the real DOM is very high. For example, sometimes we modify a certain data. If we directly render it to the real DOM, it will cause the entire DOM tree to be redrawn and rearranged. Is it possible that we only update the small piece of dom we modified instead of updating the entire dom? The diff algorithm can help us. We first generate avirtual DOM based on the real DOM. When the data of a
virtual DOM changes, a new
Vnode## will be generated. #, and then compare Vnode
with oldVnode
. If you find any differences, modify them directly on the real DOM, and then make the value of oldVnode
be Vnode
. The process of diff is to call the
named patch
, compare the old and new nodes, and patch the real DOM while comparing.
Virtual DOM extracts the real DOM data and simulates the tree structure in the form of
object. For example, the dom is like this: <p>
<p>123</p>
</p>
The corresponding virtual DOM (pseudocode):
var Vnode = { tag: 'p', children: [ { tag: 'p', text: '123' } ] };
(warm reminder:
VNode and oldVNode
are both Object, be sure to remember)
When using the diff algorithm to compare old and new nodes, the comparison will only be performed at the same level, and will not be compared across levels.
<p> <p>123</p> </p>456
The above code will compare two p on the same layer and p and span on the second layer, but will not compare p and span. A very vivid picture I saw elsewhere:
diff flow chartWhen the data changes, the set method Will call
Dep.notify to notify all subscriber Watchers, and the subscribers will call patch
to patch the real DOM and update the corresponding view
.
patch
Let’s take a look
patch How to patch (only the core part of the code is retained) <pre class="brush:php;toolbar:false">function patch (oldVnode, vnode) {
// some code
if (sameVnode(oldVnode, vnode)) {
patchVnode(oldVnode, vnode)
} else {
const oEl = oldVnode.el // 当前oldVnode对应的真实元素节点
let parentEle = api.parentNode(oEl) // 父元素
createEle(vnode) // 根据Vnode生成新元素
if (parentEle !== null) {
api.insertBefore(parentEle, vnode.el, api.nextSibling(oEl)) // 将新元素添加进父元素
api.removeChild(parentEle, oldVnode.el) // 移除以前的旧元素节点
oldVnode = null
}
}
// some code
return vnode
}</pre>
patch function receives two parameters
and Vnode
represent the new node and the previous one respectively Old node Determine whether the two nodes are worthy of comparison. If they are worthy of comparison, execute
<pre class="brush:php;toolbar:false">function sameVnode (a, b) {
return (
a.key === b.key && // key值
a.tag === b.tag && // 标签名
a.isComment === b.isComment && // 是否为注释节点
// 是否都定义了data,data包含一些具体信息,例如onclick , style
isDef(a.data) === isDef(b.data) &&
sameInputType(a, b) // 当标签是<input>的时候,type必须相同
)
}</pre>
If not worthy of comparison, replace
Vnode
If two nodes are the same, then check their child nodes in depth. If the two nodes are different, it means that
has been completely changed, and oldVnode
can be directly replaced. Although these two nodes are different, what should I do if their child nodes are the same? Don't forget, diff is compared layer by layer. If the first layer is different, then the second layer will not be compared in depth. (I wonder if this is a disadvantage? The same child node cannot be reused...)
When we determine that the two nodes are worthy of comparison, we The
patchVnode method will be assigned to both nodes. So what does this method do? <pre class="brush:php;toolbar:false">patchVnode (oldVnode, vnode) {
const el = vnode.el = oldVnode.el
let i, oldCh = oldVnode.children, ch = vnode.children
if (oldVnode === vnode) return
if (oldVnode.text !== null && vnode.text !== null && oldVnode.text !== vnode.text) {
api.setTextContent(el, vnode.text)
}else {
updateEle(el, vnode, oldVnode)
if (oldCh && ch && oldCh !== ch) {
updateChildren(el, oldCh, ch)
}else if (ch){
createEle(vnode) //create el's children dom
}else if (oldCh){
api.removeChildren(el)
}
}
}</pre>
This function does the following:
and oldVnode
point to the same object,
if They all have text nodes and are not equal, then set the text node of el
to the text node of Vnode
.
has child nodes but Vnode
does not, delete the child nodes of
el
如果 oldVnode
没有子节点而 Vnode
有,则将 Vnode
的子节点真实化之后添加到 el
如果两者都有子节点,则执行 updateChildren
函数比较子节点,这一步很重要
其他几个点都很好理解,我们详细来讲一下updateChildren
updateChildren
代码量很大,不方便一行一行的讲解,所以下面结合一些示例图来描述一下。
updateChildren (parentElm, oldCh, newCh) { let oldStartIdx = 0, 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 let idxInOld let elmToMove let before while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { if (oldStartVnode == null) { // 对于vnode.key的比较,会把oldVnode = null oldStartVnode = oldCh[++oldStartIdx] }else if (oldEndVnode == null) { oldEndVnode = oldCh[--oldEndIdx] }else if (newStartVnode == null) { newStartVnode = newCh[++newStartIdx] }else if (newEndVnode == null) { newEndVnode = newCh[--newEndIdx] }else if (sameVnode(oldStartVnode, newStartVnode)) { patchVnode(oldStartVnode, newStartVnode) oldStartVnode = oldCh[++oldStartIdx] newStartVnode = newCh[++newStartIdx] }else if (sameVnode(oldEndVnode, newEndVnode)) { patchVnode(oldEndVnode, newEndVnode) oldEndVnode = oldCh[--oldEndIdx] newEndVnode = newCh[--newEndIdx] }else if (sameVnode(oldStartVnode, newEndVnode)) { patchVnode(oldStartVnode, newEndVnode) api.insertBefore(parentElm, oldStartVnode.el, api.nextSibling(oldEndVnode.el)) oldStartVnode = oldCh[++oldStartIdx] newEndVnode = newCh[--newEndIdx] }else if (sameVnode(oldEndVnode, newStartVnode)) { patchVnode(oldEndVnode, newStartVnode) api.insertBefore(parentElm, oldEndVnode.el, oldStartVnode.el) oldEndVnode = oldCh[--oldEndIdx] newStartVnode = newCh[++newStartIdx] }else { // 使用key时的比较 if (oldKeyToIdx === undefined) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx) // 有key生成index表 } idxInOld = oldKeyToIdx[newStartVnode.key] if (!idxInOld) { api.insertBefore(parentElm, createEle(newStartVnode).el, oldStartVnode.el) newStartVnode = newCh[++newStartIdx] } else { elmToMove = oldCh[idxInOld] if (elmToMove.sel !== newStartVnode.sel) { api.insertBefore(parentElm, createEle(newStartVnode).el, oldStartVnode.el) }else { patchVnode(elmToMove, newStartVnode) oldCh[idxInOld] = null api.insertBefore(parentElm, elmToMove.el, oldStartVnode.el) } newStartVnode = newCh[++newStartIdx] } } } if (oldStartIdx > oldEndIdx) { before = newCh[newEndIdx + 1] == null ? null : newCh[newEndIdx + 1].el addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx) }else if (newStartIdx > newEndIdx) { removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx) } }
先说一下这个函数做了什么
将 Vnode
的子节点 Vch
和 oldVnode
的子节点 oldCh
提取出来
oldCh
和 vCh
各有两个头尾的变量 StartIdx
和 EndIdx
,它们的2个变量相互比较,一共有4种比较方式。如果4种比较都没匹配,如果设置了 key
,就会用 key
进行比较,在比较的过程中,变量会往中间靠,一旦 StartIdx>EndIdx
表明 oldCh
和 vCh
至少有一个已经遍历完了,就会结束比较。
图解updateChildren
终于来到了这一部分,上面的总结相信很多人也看得一脸懵逼,下面我们好好说道说道。(这都是我自己画的,求推荐好用的画图工具...)
粉红色的部分为oldCh和vCh
我们将它们取出来并分别用s和e指针指向它们的头child和尾child
现在分别对 oldS、oldE、S、E
两两做 sameVnode
比较,有四种比较方式,当其中两个能匹配上那么真实dom中的相应节点会移到Vnode相应的位置,这句话有点绕,打个比方
如果是oldS和E匹配上了,那么真实dom中的第一个节点会移到最后
如果是oldE和S匹配上了,那么真实dom中的最后一个节点会移到最前,匹配上的两个指针向中间移动
如果四种匹配没有一对是成功的,那么遍历 oldChild
, S
挨个和他们匹配,匹配成功就在真实dom中将成功的节点移到最前面,如果依旧没有成功的,那么将 S对应的节点
插入到dom中对应的 oldS
位置, oldS
和 S
指针向中间移动。
再配个图
第一步
oldS = a, oldE = d; S = a, E = b;
oldS
和 S
匹配,则将dom中的a节点放到第一个,已经是第一个了就不管了,此时dom的位置为:a b d
第二步
oldS = b, oldE = d; S = c, E = b;
oldS
和 E
匹配,就将原本的b节点移动到最后,因为 E
是最后一个节点,他们位置要一致,这就是上面说的: 当其中两个能匹配上那么真实dom中的相应节点会移到Vnode相应的位置 ,此时dom的位置为:a d b
第三步
oldS = d, oldE = d; S = c, E = d;
oldE
和 E
匹配,位置不变此时dom的位置为:a d b
第四步
oldS++; oldE--; oldS > oldE;
遍历结束,说明 oldCh
先遍历完。就将剩余的 vCh
节点根据自己的的index插入到真实dom中去,此时dom位置为:a c d b
一次模拟完成。
这个匹配过程的结束有两个条件:
oldS > oldE
表示 oldCh
先遍历完,那么就将多余的 vCh
根据index添加到dom中去(如上图) S > E
表示vCh先遍历完,那么就在真实dom中将区间为 [oldS, oldE]
的多余节点删掉
下面再举一个例子,可以像上面那样自己试着模拟一下
当这些节点 sameVnode
成功后就会紧接着执行 patchVnode
了,可以看一下上面的代码
if (sameVnode(oldStartVnode, newStartVnode)) { patchVnode(oldStartVnode, newStartVnode) }
就这样层层递归下去,直到将oldVnode和Vnode中的所有子节点比对完。也将dom的所有补丁都打好啦。那么现在再回过去看updateChildren的代码会不会容易很多呢?
总结
以上为diff算法的全部过程,放上一张文章开始就发过的总结图,可以试试看着这张图回忆一下diff的过程。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to use the diff algorithm in vue. For more information, please follow other related articles on the PHP Chinese website!