JAVASCRIPT
Using `Teleport` for Modals and Global Overlays
Master Vue 3's `Teleport` feature to render components like modals, tooltips, or notifications outside their parent DOM hierarchy for better z-index and accessibility control.
// components/ModalDialog.vue
<template>
<teleport to="body">
<div v-if="isOpen" class="modal-backdrop" @click.self="closeModal">
<div class="modal-content">
<h2>{{ title }}</h2>
<slot></slot>
<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: 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: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
min-width: 300px;
text-align: center;
}
</style>
// App.vue
<template>
<div>
<h1>Teleport Example</h1>
<button @click="showModal = true">Open Modal</button>
<ModalDialog :is-open="showModal" title="My Awesome Modal" @close="showModal = false">
<p>This content is rendered in the modal.</p>
<p>Even though it's declared here, it teleports to the body!</p>
</ModalDialog>
</div>
</template>
<script setup>
import { ref } from 'vue';
import ModalDialog from './components/ModalDialog.vue';
const showModal = ref(false);
</script>
How it works: The `Teleport` component in Vue 3 allows you to render a portion of your component's template into a different part of the DOM, outside of its logical parent. In this example, `ModalDialog` uses `Teleport` to render its content directly into the `<body>` element, ensuring it appears on top of other content regardless of its parent's z-index or overflow properties, which is ideal for modals, notifications, or tooltips.