diff算法
vue3 diff算法原码地址: https://github.com/vuejs/core
1. diff 算法主要是说renderer.ts中patchChildren这段代码逻辑,如下:
2. diff算法排序分为无key时diff算法排序逻辑和有key时diff算法排序逻辑
2.1 无key时diff算法排序逻辑, 分为三步如下,如图1中无key:
* 通过for循环patch重新渲染元素,来替换
* 删除
* 新增
const patchUnkeyedChildren = ( c1: VNode[], c2: VNodeArrayChildren, container: RendererElement, anchor: RendererNode | null, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, isSVG: boolean, slotScopeIds: string[] | null, optimized: boolean ) => { c1 = c1 || EMPTY_ARR c2 = c2 || EMPTY_ARR const oldLength = c1.length const newLength = c2.length const commonLength = Math.min(oldLength, newLength) let i for (i = 0; i < commonLength; i++) { const nextChild = (c2[i] = optimized ? cloneIfMounted(c2[i] as VNode) : normalizeVNode(c2[i])) //1. 循环patch替换 patch( c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized ) } //2. 删除 if (oldLength > newLength) { // remove old unmountChildren( c1, parentComponent, parentSuspense, true, false, commonLength ) } else { //3. 新增 // mount new mountChildren( c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, commonLength ) } }
2.2 有key时diff算法排序逻辑分为五步如下:
* 前序算法前面元素与前面元素比较如 isSameVNodeType,如果不一样,跳出循环
* 尾序算法尾和尾比较,如果不一样,跳出循环
* 新节点如果多出来就挂载(新增)
* 旧节点如果多出来就卸载(删除)
* 乱序
图1
参考文章: https://xiaoman.blog.csdn.net/article/details/122778560?spm=1001.2014.3001.5502
标签:const,dom,算法,key,vue3,diff,c1,c2 From: https://www.cnblogs.com/TheYouth/p/17532528.html