JAVASCRIPT
Teleporting Vue 3 Component Content to Any DOM Target
Utilize Vue 3's `<Teleport>` component to render a part of your component's template into a different location in the DOM, perfect for modals and notifications.
<script setup>
import { ref } from 'vue';
const showModal = ref(false);
function openModal() {
showModal.value = true;
}
function closeModal() {
showModal.value = false;
}
</script>
<template>
<div>
<h1>Teleport Demo</h1>
<p>This content is inside the main app component.</p>
<button @click="openModal">Open Modal</button>
<Teleport to="body">
<div v-if="showModal" class="modal-overlay">
<div class="modal-content">
<h2>My Teleported Modal</h2>
<p>This modal is rendered directly into the body, outside the app's DOM hierarchy.</p>
<button @click="closeModal">Close Modal</button>
</div>
</div>
</Teleport>
</div>
</template>
<style>
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.6);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.modal-content {
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
text-align: center;
}
</style>
How it works: This snippet demonstrates Vue 3's `<Teleport>` component, which allows you to move a portion of your component's template into a different DOM node that exists outside the current component's hierarchy. This is incredibly useful for elements like modals, notifications, or tooltips that need to be rendered at the `body` level (or another specific target) to avoid CSS `z-index` or overflow issues from parent components, while still maintaining their reactive state and logic within the original component. The `to` prop specifies the target CSS selector or actual DOM element.