diff --git a/packages/runtime-core/__tests__/components/KeepAlive.spec.ts b/packages/runtime-core/__tests__/components/KeepAlive.spec.ts index 79e7811723a..d7922ac0330 100644 --- a/packages/runtime-core/__tests__/components/KeepAlive.spec.ts +++ b/packages/runtime-core/__tests__/components/KeepAlive.spec.ts @@ -882,6 +882,42 @@ describe('KeepAlive', () => { expect(serializeInner(root)).toBe('

1

') }) + // #7276 + test('should invoke onActivated of child on initial mount', async () => { + let parentCount = 0 + let childCount = 0 + const Child = defineComponent({ + name: 'Child', + setup() { + onActivated(() => { + childCount++ + }) + return () => 'child' + } + }) + const Parent = defineComponent({ + setup() { + onActivated(() => { + parentCount++ + }) + return () => h(Child) + } + }) + const AsyncComp = defineAsyncComponent(() => Promise.resolve(Parent)) + + const App = { + render: () => { + return h(KeepAlive, null, () => h(AsyncComp)) + } + } + + render(h(App), root) + await timeout() + expect(serializeInner(root)).toBe('child') + expect(parentCount).toBe(1) + expect(childCount).toBe(1) + }) + // #4976 test('handle error in async onActivated', async () => { const err = new Error('foo') diff --git a/packages/runtime-core/src/components/KeepAlive.ts b/packages/runtime-core/src/components/KeepAlive.ts index 554b9f2451c..7a203072b7f 100644 --- a/packages/runtime-core/src/components/KeepAlive.ts +++ b/packages/runtime-core/src/components/KeepAlive.ts @@ -401,10 +401,18 @@ function registerKeepAliveHook( // arrays. if (target) { let current = target.parent + let child = target while (current && current.parent) { if (isKeepAlive(current.parent.vnode)) { - injectToKeepAliveRoot(wrappedHook, type, target, current) + injectToKeepAliveRoot( + wrappedHook, + type, + target, + // #7276 + isAsyncWrapper(current) ? child : current + ) } + child = current current = current.parent } }