One of the standout features introduced in Vue 3 is <teleport>, which allows you to render a component or element outside of its parent DOM hierarchy. This is especially useful for modals, tooltips, dropdowns, or overlays that need to break out of container boundaries.
How to Use <teleport>
<template>
<div class="app-container">
<button @click="showModal = true">Open Modal</button>
<!-- Teleporting the modal to the body -->
<teleport to="body">
<div v-if="showModal" class="modal-overlay">
<div class="modal-content">
<h2>I'm Teleported!</h2>
<button @click="showModal = false">Close</button>
</div>
</div>
</teleport>
</div>
</template>
<script setup>
import { ref } from 'vue';
const showModal = ref(false);
</script>
<style scoped>
.modal-overlay {
position: fixed;
top: 0; left: 0; right: 0; bottom: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
.modal-content {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}
</style>
💡 Why It’s Useful:
- Avoid CSS Issues: Teleport content to outside restrictive containers without z-index conflicts.
- Flexible UI: Perfect for modals, dropdowns, or notifications that need global placement.
- Easy Syntax: Just wrap your component with
<teleport to="body">and Vue handles the rest.
Vue 3’s <teleport> makes complex UI patterns simpler, more flexible, and cleaner to implement.