JAVASCRIPT
Teleporting a Modal to the Body in Vue 3
Learn how to use Vue 3's Teleport feature to move a modal component's DOM outside of its parent, preventing z-index issues and ensuring proper overlay behavior.
<!-- App.vue -->
<template>
<button @click="isOpen = true">Open Modal</button>
<MyModal :is-open="isOpen" @close="isOpen = false" />
</template>
<script setup>
import { ref } from 'vue';
import MyModal from './components/MyModal.vue';
const isOpen = ref(false);
</script>
<!-- components/MyModal.vue -->
<template>
<teleport to="body">
<div v-if="isOpen" class="modal-overlay" @click.self="$emit('close')">
<div class="modal-content">
<h2>Modal Title</h2>
<p>This modal content is teleported to the body!</p>
<button @click="$emit('close')">Close</button>
</div>
</div>
</teleport>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
defineProps({
isOpen: {
type: Boolean,
default: false
}
});
defineEmits(['close']);
</script>
<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>
How it works: This snippet demonstrates Vue 3's `Teleport` component to render a modal's content directly into the `body` element, regardless of where `MyModal` is used in the component tree. This is crucial for modals, tooltips, or notifications to avoid CSS stacking context and `z-index` issues within nested components, ensuring the overlay always appears on top of everything else.