JAVASCRIPT
Building Accessible Modals with Vue 3 Teleport
Learn to create modals, tooltips, or notifications that render outside their parent component's DOM hierarchy using Vue 3's `<Teleport>` feature, improving accessibility and styling.
<!-- App.vue -->
<template>
<div>
<h1>Vue 3 Teleport Example</h1>
<p>Content below the teleport target.</p>
<button @click="showModal = true">Open Modal</button>
<MyModal :show="showModal" @close="showModal = false" />
</div>
</template>
<script setup>
import { ref } from 'vue';
import MyModal from './components/MyModal.vue';
const showModal = ref(false);
</script>
<!-- MyModal.vue -->
<template>
<Teleport to="body">
<div v-if="show" 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({
show: {
type: Boolean,
default: false
}
});
defineEmits(['close']);
</script>
<style>
.modal-overlay {
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: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
</style>
How it works: This snippet demonstrates Vue 3's `<Teleport>` component to render content (like a modal) into a different part of the DOM, typically `body`, even though it's defined within a nested component. This is crucial for handling z-index issues, ensuring accessibility, and avoiding styling conflicts that can arise when modals are rendered deep within the component tree. The `to` prop specifies the target DOM element where the content should be moved, making it incredibly flexible for complex UI structures.