JAVASCRIPT
Render Content Outside Component with Teleport
Use Vue 3's `<Teleport>` component to render a modal or overlay's content directly into the `body` or another target DOM element, preventing z-index and styling issues.
// src/components/Modal.vue
<template>
<Teleport to="body">
<div v-if="isOpen" class="modal-overlay" @click.self="$emit('close')">
<div class="modal-content">
<slot></slot>
<button @click="$emit('close')" class="modal-close-button">X</button>
</div>
</div>
</Teleport>
</template>
<script setup>
defineProps({
isOpen: {
type: Boolean,
required: true,
},
});
defineEmits(['close']);
</script>
<style scoped>
.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: 1000;
}
.modal-content {
background: white;
padding: 20px;
border-radius: 8px;
min-width: 300px;
position: relative;
}
.modal-close-button {
position: absolute;
top: 10px;
right: 10px;
background: none;
border: none;
font-size: 1.2em;
cursor: pointer;
}
</style>
// src/App.vue (Usage)
<template>
<div>
<h1>Teleport Example</h1>
<button @click="isModalOpen = true">Open Modal</button>
<Modal :is-open="isModalOpen" @close="isModalOpen = false">
<h2>Modal Title</h2>
<p>This content is rendered in the modal.</p>
<p>Despite being defined inside App.vue, it appears in the document body.</p>
</Modal>
</div>
</template>
<script setup>
import { ref } from 'vue';
import Modal from './components/Modal.vue';
const isModalOpen = ref(false);
</script>
How it works: This snippet demonstrates Vue 3's `<Teleport>` component, which allows you to render a component's content into a different part of the DOM tree, outside of its parent component's hierarchy. Here, a `Modal` component uses `<Teleport to="body">` to render its overlay and content directly into the document's `body` element. This is extremely useful for modals, tooltips, or notifications, as it prevents z-index, overflow, and styling issues that can arise when these elements are deeply nested within a component's structure.