JAVASCRIPT
Using Vue 3 Teleport to Render Content Outside Component Hierarchy
Learn how to use Vue 3's <Teleport> feature to render content into a different part of the DOM, perfect for modals, tooltips, or notifications.
<!-- index.html (or public/index.html) -->
<body>
<div id="app"></div>
<div id="modal-root"></div> <!-- Target for Teleport -->
</body>
<!-- App.vue -->
<template>
<div>
<h1>Teleport Example</h1>
<button @click="showModal = true">Open Modal</button>
<teleport to="#modal-root">
<div v-if="showModal" class="modal-overlay">
<div class="modal-content">
<h2>My Teleported Modal</h2>
<p>This content is rendered in a different DOM tree!</p>
<button @click="showModal = false">Close Modal</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;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.modal-content {
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
text-align: center;
}
.modal-content button {
margin-top: 15px;
padding: 8px 15px;
cursor: pointer;
}
</style>
How it works: Vue 3's `<Teleport>` component allows you to render a part of your component's template into a different DOM node that exists outside the component's own DOM hierarchy. This is incredibly useful for managing elements like modals, tooltips, and notifications, ensuring they are correctly positioned at the top of the DOM stack (e.g., directly under `body`) without complex z-index issues or impacting the component's styling scope. The `to` prop specifies the target DOM element using a CSS selector.