Skip to content

Commit c71a08e

Browse files
authored
fix(runtime-core): Lifecycle hooks should support callbacks shared by reference (#6687)
fix #6686
1 parent 96ba71d commit c71a08e

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

packages/runtime-core/__tests__/apiLifecycle.spec.ts

+23
Original file line numberDiff line numberDiff line change
@@ -378,4 +378,27 @@ describe('api: lifecycle hooks', () => {
378378
newValue: 3
379379
})
380380
})
381+
382+
it('runs shared hook fn for each instance', async () => {
383+
const fn = jest.fn()
384+
const toggle = ref(true)
385+
const Comp = {
386+
setup() {
387+
return () => (toggle.value ? [h(Child), h(Child)] : null)
388+
}
389+
}
390+
const Child = {
391+
setup() {
392+
onMounted(fn)
393+
onBeforeUnmount(fn)
394+
return () => h('div')
395+
}
396+
}
397+
398+
render(h(Comp), nodeOps.createElement('div'))
399+
expect(fn).toHaveBeenCalledTimes(2)
400+
toggle.value = false
401+
await nextTick()
402+
expect(fn).toHaveBeenCalledTimes(4)
403+
})
381404
})

packages/runtime-core/src/apiLifecycle.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ export const createHook =
6868
(hook: T, target: ComponentInternalInstance | null = currentInstance) =>
6969
// post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
7070
(!isInSSRComponentSetup || lifecycle === LifecycleHooks.SERVER_PREFETCH) &&
71-
injectHook(lifecycle, hook, target)
71+
injectHook(lifecycle, (...args: unknown[]) => hook(...args), target)
7272

7373
export const onBeforeMount = createHook(LifecycleHooks.BEFORE_MOUNT)
7474
export const onMounted = createHook(LifecycleHooks.MOUNTED)

0 commit comments

Comments
 (0)