JAVASCRIPT
Use Vue 3 Teleport for Modals and Global Overlays
Render component content outside its parent hierarchy with Vue 3's Teleport. Perfect for creating accessible modals, tooltips, and notifications.
// index.html (ensure a target element exists)
<body>
<div id="app"></div>
<div id="modal-root"></div> <!-- Teleport target -->
</body>
// components/MyModal.vue
<script setup>
import { ref } from 'vue';
const showModal = ref(false);
const openModal = () => {
showModal.value = true;
};
const closeModal = () => {
showModal.value = false;
};
</script>
<template>
<button @click="openModal">Open Modal</button>
<teleport to="#modal-root">
<div v-if="showModal" class="modal-overlay" @click.self="closeModal">
<div class="modal-content">
<h2>Welcome to the Modal!</h2>
<p>This content is rendered outside the app's DOM hierarchy.</p>
<button @click="closeModal">Close Modal</button>
</div>
</div>
</teleport>
<style scoped>
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.modal-content {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
z-index: 1001;
}
</style>
</template>
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 modals, notifications, or tooltips, ensuring they are correctly positioned and z-indexed regardless of where the component itself is nested. The `to` prop specifies the target CSS selector or actual DOM element where the content should be moved.