JAVASCRIPT
Managing Modals and Overlays with Vue 3's `<Teleport>`
Use Vue 3's built-in `<Teleport>` component to render modal dialogs, tooltips, or notifications into a different part of the DOM, avoiding styling and z-index issues.
// ModalComponent.vue
<template>
<Teleport to="body">
<div v-if="isOpen" class="modal-backdrop" @click.self="closeModal">
<div class="modal-content">
<h3>{{ title }}</h3>
<slot>Default Modal Content</slot>
<button @click="closeModal">Close</button>
</div>
</div>
</Teleport>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps({
isOpen: {
type: Boolean,
default: false
},
title: {
type: String,
default: 'Modal Title'
}
});
const emit = defineEmits(['update:isOpen']);
const closeModal = () => {
emit('update:isOpen', false);
};
</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 10px rgba(0, 0, 0, 0.1);
max-width: 500px;
width: 90%;
z-index: 1001;
}
</style>
// App.vue (or any parent component)
<template>
<div>
<button @click="isModalOpen = true">Open Modal</button>
<ModalComponent v-model:isOpen="isModalOpen" title="My Awesome Modal">
<p>This content is inside the modal.</p>
<p>It's rendered in the body thanks to Teleport!</p>
</ModalComponent>
</div>
</template>
<script setup>
import { ref } from 'vue';
import ModalComponent from './ModalComponent.vue';
const isModalOpen = ref(false);
</script>
How it works: This snippet demonstrates Vue 3's `<Teleport>` component, a powerful feature for rendering a part of a component's template into a different DOM node outside its parent-child hierarchy. This is particularly useful for modals, tooltips, and notifications, allowing them to escape their component's styling and z-index contexts and render directly to the `body` or another target, simplifying layout and positioning.