What is Vue's Teleport component?
Answer
<Teleport> (Vue 3) renders a component's content in a different DOM location than where it's declared in the component tree — "teleporting" it to another DOM node. Usage: <Teleport to="body"> <div class="modal"> <h2>Modal Title</h2> <p>Modal content</p> </div> </Teleport>. The to attribute is a CSS selector string (or DOM element). The modal is rendered as a child of <body> in the actual DOM, even though it's declared inside a deeply nested component. Why is this useful? (1) Modals and overlays: modals should render at the document root to avoid CSS stacking context issues (overflow: hidden on parents, z-index problems, transforms affecting fixed positioning); (2) Tooltips and popovers: same reasoning; (3) Notifications/toasts: always render in a fixed position relative to the viewport. Still in component tree: despite teleporting, the component's logic (props, events, provide/inject, lifecycle) remains in the original component tree — only the rendered output is moved. Parent context (theme, auth) is still accessible. disabled: <Teleport :disabled="isMobile" to="body"> — conditionally disable teleportation. Multiple Teleports: multiple teleports to the same target are appended in order. Equivalent in React: React Portals (ReactDOM.createPortal).
Previous
What is the defineProps and defineEmits in Vue 3 script setup?
Next
What are Vue composables?