Skip to content

Commit 7e08418

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

File tree

1 file changed

+24
-10
lines changed

1 file changed

+24
-10
lines changed

packages/runtime-core/src/renderer.ts

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -498,15 +498,27 @@ 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 =
514+
container.childNodes[
515+
((n2 as any).__elIndex = (n1 as any).__elIndex)
516+
]
517+
hostInsert(newChild, container, oldChild)
518+
hostRemove(oldChild)
519+
} else {
520+
hostSetText(el, n2.children as string)
508521
}
509-
hostSetText(el, n2.children as string)
510522
}
511523
}
512524
}
@@ -2502,12 +2514,14 @@ export function traverseStaticChildren(
25022514
traverseStaticChildren(c1, c2)
25032515
}
25042516
// #6852 also inherit for text nodes
2505-
if (
2506-
c2.type === Text &&
2517+
if (c2.type === Text) {
25072518
// avoid cached text nodes retaining detached dom nodes
2508-
c2.patchFlag !== PatchFlags.CACHED
2509-
) {
2510-
c2.el = c1.el
2519+
if (c2.patchFlag !== PatchFlags.CACHED) {
2520+
c2.el = c1.el
2521+
} else {
2522+
// cache the child index for HMR updates
2523+
;(c2 as any).__elIndex = i + (n1.type === Fragment ? 1 : 0)
2524+
}
25112525
}
25122526
// #2324 also inherit for comment nodes, but not placeholders (e.g. v-if which
25132527
// would have received .el during block patch)

0 commit comments

Comments
 (0)