JAVASCRIPT
Vue 3 Teleport for Rendering Modals and Overlays
Master Vue 3's `Teleport` component to render content (like modals, notifications) into a different part of the DOM tree, avoiding z-index and overflow issues.
// components/App.vue
<template>
<h1>My Vue App</h1>
<p>This is the main content.</p>
<button @click="showModal = true">Open Modal</button>
<Teleport to="body">
<div v-if="showModal" class="modal-overlay">
<div class="modal-content">
<h2>Welcome to the Modal!</h2>
<p>This modal is rendered outside the app's DOM hierarchy, directly into the body.</p>
<button @click="showModal = false">Close Modal</button>
</div>
</div>
</Teleport>
<div id="another-target"></div>
<Teleport to="#another-target">
<p v-if="showModal" style="color: blue;">This text is teleported to '#another-target'!</p>
</Teleport>
</template>
<script setup>
import { ref } from 'vue';
const showModal = ref(false);
</script>
<style>
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 999;
}
.modal-content {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
max-width: 500px;
width: 90%;
}
</style>
How it works: The `Teleport` component in Vue 3 allows you to render a component's content into a different part of the DOM tree, even outside of the app's mounted element. This is extremely useful for handling modals, notifications, or tooltips that might run into CSS `z-index` or `overflow` clipping issues if rendered directly within their parent components. By specifying a `to` target (e.g., `'body'` or an ID selector), the content is moved while maintaining its reactive connection to the component's state.