How to Use Teleport in Vue: Simple Guide with Examples
In Vue, use the
Teleport component to render part of your template outside its parent DOM hierarchy by specifying a to target selector. This is useful for modals, tooltips, or overlays that need to appear elsewhere in the DOM.Syntax
The <Teleport> component wraps the content you want to move and requires a to attribute that specifies the CSS selector of the target element in the DOM.
Inside <Teleport to="selector">, place the content you want to render elsewhere.
vue
<Teleport to="#target">
<div>This content is teleported!</div>
</Teleport>Output
The div with text 'This content is teleported!' appears inside the element with id 'target' in the DOM.
Example
This example shows a button that toggles a modal dialog. The modal content is teleported to a <div id="modal-root"> outside the main app container.
vue
<template>
<div>
<button @click="showModal = true">Open Modal</button>
<Teleport to="#modal-root">
<div v-if="showModal" class="modal">
<p>This modal is teleported outside the app root.</p>
<button @click="showModal = false">Close</button>
</div>
</Teleport>
</div>
</template>
<script setup>
import { ref } from 'vue'
const showModal = ref(false)
</script>
<style>
.modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: white;
padding: 1rem;
border: 1px solid #ccc;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
</style>Output
When clicking 'Open Modal', a modal box appears centered on the screen, rendered inside the #modal-root element outside the main app container.
Common Pitfalls
- Not having the target element in the DOM before teleporting causes the content not to render.
- Using an invalid or missing CSS selector in
towill fail silently. - Teleport does not move reactive state; it only changes where the content is rendered.
vue
<!-- Wrong: target element missing --> <Teleport to="#missing-root"> <div>Won't appear</div> </Teleport> <!-- Right: ensure target exists --> <div id="missing-root"></div> <Teleport to="#missing-root"> <div>Now it appears</div> </Teleport>
Output
The first teleport content does not appear because #missing-root is not in the DOM; the second appears correctly after adding the target element.
Quick Reference
Teleport Component Cheat Sheet:
to: CSS selector string for the target container.- Wrap any content inside
<Teleport>to render it elsewhere. - Works well for modals, dropdowns, tooltips, and overlays.
- Target element must exist in the DOM before teleporting.
- Reactive data and events work normally inside teleported content.
Key Takeaways
Use
Teleport with a valid to selector to render content outside its parent DOM.Ensure the target element exists in the DOM before teleporting content.
Teleport is ideal for UI elements like modals and tooltips that need to appear elsewhere.
Reactive state and events work normally inside teleported content.
Avoid missing or incorrect target selectors to prevent silent failures.