Skip to content

Commit a223e68

Browse files
committed
fix: improve HMR updates for cached text nodes by replacing them
1 parent c70913b commit a223e68

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

packages/runtime-core/src/renderer.ts

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -498,15 +498,24 @@ function baseCreateRenderer(
498498
anchor,
499499
)
500500
} else {
501-
let el = (n2.el = n1.el!)
501+
const el = (n2.el = n1.el!)
502502
if (n2.children !== n1.children) {
503503
// we don't inherit text node for cached text nodes in `traverseStaticChildren`
504504
// but it maybe changed during HMR updates, so we need to handle this case by
505-
// creating a new text node.
506-
if (__DEV__ && isHmrUpdating && n2.patchFlag === PatchFlags.CACHED) {
507-
el = hostCreateText(n2.children as string)
505+
// replacing the text node.
506+
if (
507+
__DEV__ &&
508+
isHmrUpdating &&
509+
n2.patchFlag === PatchFlags.CACHED &&
510+
'__elIndex' in n1
511+
) {
512+
const newChild = hostCreateText(n2.children as string)
513+
const oldChild = container.childNodes[(n1 as any).__elIndex]
514+
hostInsert(newChild, container, oldChild)
515+
hostRemove(oldChild)
516+
} else {
517+
hostSetText(el, n2.children as string)
508518
}
509-
hostSetText(el, n2.children as string)
510519
}
511520
}
512521
}
@@ -2502,12 +2511,14 @@ export function traverseStaticChildren(
25022511
traverseStaticChildren(c1, c2)
25032512
}
25042513
// #6852 also inherit for text nodes
2505-
if (
2506-
c2.type === Text &&
2514+
if (c2.type === Text) {
25072515
// avoid cached text nodes retaining detached dom nodes
2508-
c2.patchFlag !== PatchFlags.CACHED
2509-
) {
2510-
c2.el = c1.el
2516+
if (c2.patchFlag !== PatchFlags.CACHED) {
2517+
c2.el = c1.el
2518+
} else {
2519+
// cache the child index for HMR updates
2520+
;(c2 as any).__elIndex = i + (n1.type === Fragment ? 1 : 0)
2521+
}
25112522
}
25122523
// #2324 also inherit for comment nodes, but not placeholders (e.g. v-if which
25132524
// would have received .el during block patch)

0 commit comments

Comments
 (0)