JAVASCRIPT
Implementing Modals and Overlays with Vue 3 Teleport
Leverage Vue 3's `<Teleport>` component to render modal windows, tooltips, or any UI element directly into a specific DOM target outside its component's hierarchy.
// components/MyModal.vue
<template>
<Teleport to="body">
<div v-if="isOpen" class="modal-backdrop" @click.self="closeModal">
<div class="modal-content">
<h2>{{ title }}</h2>
<p><slot>Default modal content.</slot></p>
<button @click="closeModal">Close</button>
</div>
</div>
</Teleport>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps({
isOpen: {
type: Boolean,
required: true
},
title: {
type: String,
default: 'Modal Title'
}
});
const emit = defineEmits(['close']);
function closeModal() {
emit('close');
}
</script>
<style scoped>
.modal-backdrop {
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-color: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
max-width: 500px;
text-align: center;
}
</style>
// App.vue (or parent component)
<template>
<div>
<h1>Welcome to My App</h1>
<button @click="isModalOpen = true">Open Modal</button>
<MyModal :isOpen="isModalOpen" title="Important Message" @close="isModalOpen = false">
<p>This is the content of the modal, rendered by Teleport!</p>
<p>It can contain any HTML or other components.</p>
</MyModal>
</div>
</template>
<script setup>
import { ref } from 'vue';
import MyModal from './components/MyModal.vue';
const isModalOpen = ref(false);
</script>
How it works: This snippet showcases Vue 3's `<Teleport>` component, which allows a component's content to be rendered into a different DOM node, even outside the component's immediate parent hierarchy. Here, `MyModal.vue` uses `<Teleport to="body">` to render its entire structure directly into the `body` of the document, ensuring it overlays all other content. This is ideal for modals, notifications, or tooltips, preventing z-index or overflow issues from parent components. The modal's visibility is controlled via a prop, and an emit event handles closing.