Skip to content

Commit 890ca8a

Browse files
authored
fix(keep-alive): should use onMounted and onUpdated to invoke cacheSubtree (#1984)
1 parent 0d4910a commit 890ca8a

File tree

2 files changed

+46
-4
lines changed

2 files changed

+46
-4
lines changed

packages/runtime-core/__tests__/components/KeepAlive.spec.ts

+42
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,48 @@ describe('KeepAlive', () => {
131131
assertHookCalls(two, [1, 1, 2, 2, 1])
132132
})
133133

134+
test('should call correct lifecycle hooks when toggle the KeepAlive first', async () => {
135+
const toggle = ref(true)
136+
const viewRef = ref('one')
137+
const App = {
138+
render() {
139+
return toggle.value ? h(KeepAlive, () => h(views[viewRef.value])) : null
140+
}
141+
}
142+
render(h(App), root)
143+
144+
expect(serializeInner(root)).toBe(`<div>one</div>`)
145+
assertHookCalls(one, [1, 1, 1, 0, 0])
146+
assertHookCalls(two, [0, 0, 0, 0, 0])
147+
148+
// should unmount 'one' component when toggle the KeepAlive first
149+
toggle.value = false
150+
await nextTick()
151+
expect(serializeInner(root)).toBe(`<!---->`)
152+
assertHookCalls(one, [1, 1, 1, 1, 1])
153+
assertHookCalls(two, [0, 0, 0, 0, 0])
154+
155+
toggle.value = true
156+
await nextTick()
157+
expect(serializeInner(root)).toBe(`<div>one</div>`)
158+
assertHookCalls(one, [2, 2, 2, 1, 1])
159+
assertHookCalls(two, [0, 0, 0, 0, 0])
160+
161+
// 1. the first time toggle kept-alive component
162+
viewRef.value = 'two'
163+
await nextTick()
164+
expect(serializeInner(root)).toBe(`<div>two</div>`)
165+
assertHookCalls(one, [2, 2, 2, 2, 1])
166+
assertHookCalls(two, [1, 1, 1, 0, 0])
167+
168+
// 2. should unmount all components including cached
169+
toggle.value = false
170+
await nextTick()
171+
expect(serializeInner(root)).toBe(`<!---->`)
172+
assertHookCalls(one, [2, 2, 2, 2, 2])
173+
assertHookCalls(two, [1, 1, 1, 1, 1])
174+
})
175+
134176
test('should call lifecycle hooks on nested components', async () => {
135177
one.render = () => h(two)
136178

packages/runtime-core/src/components/KeepAlive.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ import {
1313
onBeforeUnmount,
1414
injectHook,
1515
onUnmounted,
16-
onBeforeMount,
17-
onBeforeUpdate
16+
onMounted,
17+
onUpdated
1818
} from '../apiLifecycle'
1919
import {
2020
isString,
@@ -187,8 +187,8 @@ const KeepAliveImpl = {
187187
cache.set(pendingCacheKey, instance.subTree)
188188
}
189189
}
190-
onBeforeMount(cacheSubtree)
191-
onBeforeUpdate(cacheSubtree)
190+
onMounted(cacheSubtree)
191+
onUpdated(cacheSubtree)
192192

193193
onBeforeUnmount(() => {
194194
cache.forEach(cached => {

0 commit comments

Comments
 (0)