Sometimes a component needs to render elements that should visually break out of the parent container.
The most common examples are full-screen Modal popups, tooltips, and dropdown notifications.
Because of complex CSS issues like overflow: hidden or z-index stacking, it is dangerous to render a Modal deep inside the DOM tree.
<Teleport>Vue provides a built-in component called <Teleport>.
Teleport allows us to define our component logic perfectly where it belongs in the code.
However, it physically "teleports" the actual HTML rendering to a completely different location in the DOM (like the <body> tag)!
To use teleport, simply wrap your HTML inside the <Teleport> tag.
You must provide a to attribute, which takes a standard CSS selector (like body or #modal-root).
Vue will grab the content and surgically inject it into that target element!
<template> <button @click="open = true">Open Modal</button><!-- Teleporting the modal to the very top body tag! --> <Teleport to="body"> <div v-if="open" class="modal"> <p>Hello from the modal!</p> <button @click="open = false">Close</button> </div> </Teleport> </template>
The magic of Teleport is that it only moves the actual HTML rendering.
The component logic remains exactly where it was defined.
The teleported component can still access parent props, emit events, and read local reactive data flawlessly!
In some cases, you might want to conditionally disable the teleportation (for instance, on mobile screens).
You can pass a :disabled boolean attribute directly to the <Teleport> tag.
If disabled is true, the content will render exactly where it was written without moving.
Why is the <Teleport> tag commonly used for full-screen Modal popups?
If you teleport a component to the 'body' tag, does it lose access to its parent's reactive data?