Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(keep-alive): should use onMounted and onUpdated to invoke cacheSu… #1984

Merged
merged 1 commit into from
Sep 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions packages/runtime-core/__tests__/components/KeepAlive.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,48 @@ describe('KeepAlive', () => {
assertHookCalls(two, [1, 1, 2, 2, 1])
})

test('should call correct lifecycle hooks when toggle the KeepAlive first', async () => {
const toggle = ref(true)
const viewRef = ref('one')
const App = {
render() {
return toggle.value ? h(KeepAlive, () => h(views[viewRef.value])) : null
}
}
render(h(App), root)

expect(serializeInner(root)).toBe(`<div>one</div>`)
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [0, 0, 0, 0, 0])

// should unmount 'one' component when toggle the KeepAlive first
toggle.value = false
await nextTick()
expect(serializeInner(root)).toBe(`<!---->`)
assertHookCalls(one, [1, 1, 1, 1, 1])
assertHookCalls(two, [0, 0, 0, 0, 0])

toggle.value = true
await nextTick()
expect(serializeInner(root)).toBe(`<div>one</div>`)
assertHookCalls(one, [2, 2, 2, 1, 1])
assertHookCalls(two, [0, 0, 0, 0, 0])

// 1. the first time toggle kept-alive component
viewRef.value = 'two'
await nextTick()
expect(serializeInner(root)).toBe(`<div>two</div>`)
assertHookCalls(one, [2, 2, 2, 2, 1])
assertHookCalls(two, [1, 1, 1, 0, 0])

// 2. should unmount all components including cached
toggle.value = false
await nextTick()
expect(serializeInner(root)).toBe(`<!---->`)
assertHookCalls(one, [2, 2, 2, 2, 2])
assertHookCalls(two, [1, 1, 1, 1, 1])
})

test('should call lifecycle hooks on nested components', async () => {
one.render = () => h(two)

Expand Down
8 changes: 4 additions & 4 deletions packages/runtime-core/src/components/KeepAlive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ import {
onBeforeUnmount,
injectHook,
onUnmounted,
onBeforeMount,
onBeforeUpdate
onMounted,
onUpdated
} from '../apiLifecycle'
import {
isString,
Expand Down Expand Up @@ -187,8 +187,8 @@ const KeepAliveImpl = {
cache.set(pendingCacheKey, instance.subTree)
}
}
onBeforeMount(cacheSubtree)
onBeforeUpdate(cacheSubtree)
onMounted(cacheSubtree)
onUpdated(cacheSubtree)

onBeforeUnmount(() => {
cache.forEach(cached => {
Expand Down