From 55a3f785201efd4d4fd15a25a547b7ab00d8cd14 Mon Sep 17 00:00:00 2001 From: jaluik Date: Sun, 5 Mar 2023 10:23:08 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=89=BE=E5=88=B0=E9=9C=80=E8=A6=81?= =?UTF-8?q?=E7=A7=BB=E5=8A=A8=E7=9A=84=E5=85=83=E7=B4=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/frontEnd/sourceCode/vue3.md | 34 ++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/docs/frontEnd/sourceCode/vue3.md b/docs/frontEnd/sourceCode/vue3.md index 26dd5a4..be34685 100644 --- a/docs/frontEnd/sourceCode/vue3.md +++ b/docs/frontEnd/sourceCode/vue3.md @@ -124,3 +124,37 @@ function patchChildren(n1, n2, container) { 这里只考虑`patch`内容,下面再考虑移动`DOM`。 ### 找到需要移动的元素 + +这里的主要思路是: + +- 遍历新的`nodeList`时,如果匹配到了`key`相同的旧的`node`,则进行`patch`操作,并且此时观察此时匹配到的`index`是否仍然保持递增的序列,如果仍然保持则更新`lastIndex`为新的`index`, 否则说明需要移动`DOM`。 + +```js +function patchChildren(n1, n2, container) { + if (typeof n2.children === 'string') { + // 省略代码 + } else if (Array.isArray(n2.children)) { + const oldChildren = n1.children + const newChildren = n2.children + // 增加了lastIndex变量来记录上一次遍历到的最大index位置 + let lastIndex = 0 + for (let i = 0; i < newChildren.length; i++) { + const newNode = newChildren[i] + for (let j = 0; j < oldChildren.length; j++) { + const oldNode = oldChildren[j] + if (newNode.key === oldNode.key) { + patch(oldNode, newNode, container) + if (j < lastIndex) { + // 需要移动 + } else { + lastIndex = j + } + break + } + } + } + } else { + // 省略代码 + } +} +```