From: Thorsten Lünborg Date: Tue, 27 Sep 2022 02:18:22 +0000 (+0200) Subject: fix(runtime-core): Lifecycle hooks should support callbacks shared by reference ... X-Git-Tag: v3.2.40~19 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=c71a08e6fd44ee06c6b4f61d67727a7b7503605e;p=thirdparty%2Fvuejs%2Fcore.git fix(runtime-core): Lifecycle hooks should support callbacks shared by reference (#6687) fix #6686 --- diff --git a/packages/runtime-core/__tests__/apiLifecycle.spec.ts b/packages/runtime-core/__tests__/apiLifecycle.spec.ts index 4c27ada55c..b7e8de30d5 100644 --- a/packages/runtime-core/__tests__/apiLifecycle.spec.ts +++ b/packages/runtime-core/__tests__/apiLifecycle.spec.ts @@ -378,4 +378,27 @@ describe('api: lifecycle hooks', () => { newValue: 3 }) }) + + it('runs shared hook fn for each instance', async () => { + const fn = jest.fn() + const toggle = ref(true) + const Comp = { + setup() { + return () => (toggle.value ? [h(Child), h(Child)] : null) + } + } + const Child = { + setup() { + onMounted(fn) + onBeforeUnmount(fn) + return () => h('div') + } + } + + render(h(Comp), nodeOps.createElement('div')) + expect(fn).toHaveBeenCalledTimes(2) + toggle.value = false + await nextTick() + expect(fn).toHaveBeenCalledTimes(4) + }) }) diff --git a/packages/runtime-core/src/apiLifecycle.ts b/packages/runtime-core/src/apiLifecycle.ts index ec39308eea..f7d6d7007c 100644 --- a/packages/runtime-core/src/apiLifecycle.ts +++ b/packages/runtime-core/src/apiLifecycle.ts @@ -68,7 +68,7 @@ export const createHook = (hook: T, target: ComponentInternalInstance | null = currentInstance) => // post-create lifecycle registrations are noops during SSR (except for serverPrefetch) (!isInSSRComponentSetup || lifecycle === LifecycleHooks.SERVER_PREFETCH) && - injectHook(lifecycle, hook, target) + injectHook(lifecycle, (...args: unknown[]) => hook(...args), target) export const onBeforeMount = createHook(LifecycleHooks.BEFORE_MOUNT) export const onMounted = createHook(LifecycleHooks.MOUNTED)