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(runtime-core): Lifecycle hooks should support callbacks shared by reference (fix #6686) #6687

Merged
merged 1 commit into from Sep 27, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 23 additions & 0 deletions packages/runtime-core/__tests__/apiLifecycle.spec.ts
Expand Up @@ -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)
})
})
2 changes: 1 addition & 1 deletion packages/runtime-core/src/apiLifecycle.ts
Expand Up @@ -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)
Expand Down