]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
fix(keep-alive): should use onMounted and onUpdated to invoke cacheSubtree (#1984)
author被雨水过滤的空气 <958414905@qq.com>
Tue, 15 Sep 2020 00:50:06 +0000 (08:50 +0800)
committerGitHub <noreply@github.com>
Tue, 15 Sep 2020 00:50:06 +0000 (20:50 -0400)
packages/runtime-core/__tests__/components/KeepAlive.spec.ts
packages/runtime-core/src/components/KeepAlive.ts

index e1bf3f49b0e35528419fce4aa50057367267a8cd..27db922a264229b98ecec18bb56a58adda5444e8 100644 (file)
@@ -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)
 
index b32a6ca2795216370ec6e6fb90b2e1c7785757f2..6ef7f5f387f8515b8432259a9843a8ec0c93d4ed 100644 (file)
@@ -13,8 +13,8 @@ import {
   onBeforeUnmount,
   injectHook,
   onUnmounted,
-  onBeforeMount,
-  onBeforeUpdate
+  onMounted,
+  onUpdated
 } from '../apiLifecycle'
 import {
   isString,
@@ -187,8 +187,8 @@ const KeepAliveImpl = {
         cache.set(pendingCacheKey, instance.subTree)
       }
     }
-    onBeforeMount(cacheSubtree)
-    onBeforeUpdate(cacheSubtree)
+    onMounted(cacheSubtree)
+    onUpdated(cacheSubtree)
 
     onBeforeUnmount(() => {
       cache.forEach(cached => {