Teleport Target Removal: Does Vue 3 Clean Up Orphaned Components?
0 reputation · 03 Feb 2021, 05:00 UTC
0 reputation · 03 Feb 2021, 05:00 UTC
Investigate how Vue 3’s Teleport feature behaves when the target element is removed from the DOM after a component has been teleported. The focus is on cleanup and reattachment semantics that are not explicitly defined in the official documentation.
Teleport accepts either a selector string or a DOM element at mount time and supports dynamic target resolution. Documentation states that teleport does not automatically reattach or remove a component if the target disappears, but the exact lifecycle outcomes remain unclear across browsers and Vue releases.
32775 reputation · 03 Feb 2021, 12:10 UTC
Vue 3 does not automatically unmount a component that has been teleported when the target element is removed from the DOM after the component has mounted. The component instance remains in the Vue instance tree, but its rendered DOM node disappears because the target no longer exists.
$el.parentNode after target removal returns null, indicating the DOM node is gone, but the instance remains.To avoid memory leaks or stale state, developers should explicitly unmount or hide the teleported component when the target disappears.
v-if or v-show: Render the Teleport only when the target exists.
<template>
<div v-if="targetExists">
<Teleport :to="targetSelector">
<MyComponent />
</Teleport>
</div>
</template>
targetExists to false.
const observer = new MutationObserver((mutations) => {
if (!document.querySelector(targetSelector)) {
targetExists.value = false;
}
});
observer.observe(document.body, { childList: true, subtree: true });
onBeforeUnmount, detach observers or cancel any async tasks to prevent leaks.
No. Whether you pass a selector string or a DOM element to Teleport, Vue treats the component instance the same way. The only nuance is that with a dynamic element you must ensure the element reference stays valid; otherwise the target resolution will fail silently.
To tailor the cleanup approach for your project, please let me know which Vue 3 version you’re running (e.g., 3.0.x, 3.2.x, or the latest 3.3.x). Different patch releases may have minor adjustments to the internal lifecycle handling.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.