JAVASCRIPT
Efficiently Render Modals and Overlays with Vue 3 Teleport
Learn how to use Vue 3's <Teleport> component to render content (like modals or notifications) into a different DOM location, avoiding styling and z-index issues.
// App.vue
<template>
<div>
<h1>My App</h1>
<button @click="isModalOpen = true">Open Modal</button>
<MyModal :isOpen="isModalOpen" @close="isModalOpen = false" />
</div>
</template>
<script setup>
import { ref } from 'vue';
import MyModal from './components/MyModal.vue';
const isModalOpen = ref(false);
</script>
// components/MyModal.vue
<template>
<Teleport to="body">
<div v-if="isOpen" class="modal-backdrop" @click.self="$emit('close')">
<div class="modal-content">
<h2>Modal Title</h2>
<p>This 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: Boolean,
});
defineEmits(['close']);
</script>
<style scoped>
.modal-backdrop {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.modal-content {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
z-index: 1001;
}
</style>
How it works: Vue 3's `Teleport` component allows you to render a portion of your component's template into a different DOM location, even outside its parent component's hierarchy. This is incredibly useful for modals, notifications, or tooltips that need to appear above all other content without complex z-index or styling conflicts caused by parent components' CSS. The `to` prop specifies the target DOM element (e.g., `'body'`). This snippet demonstrates how to create a reusable modal component that 'teleports' itself to the body element.