JAVASCRIPT
Rendering Modals or Overlays with Vue 3 Teleport
Master Vue 3's Teleport feature to render component content into a different part of the DOM, perfect for accessible modals, tooltips, and global notifications.
// Base Modal Container in public/index.html
<body>
<div id="app"></div>
<div id="modal-root"></div> <!-- Target for teleported content -->
</body>
// ModalComponent.vue
<template>
<teleport to="#modal-root">
<div v-if="isOpen" class="modal-backdrop" @click.self="closeModal">
<div class="modal-content">
<h2>{{ title }}</h2>
<p><slot>Default modal content goes here.</slot></p>
<button @click="closeModal">Close</button>
</div>
</div>
</teleport>
</template>
<script setup>
import { ref } from 'vue';
const props = defineProps({
title: String
});
const isOpen = ref(false);
const openModal = () => {
isOpen.value = true;
};
const closeModal = () => {
isOpen.value = false;
};
defineExpose({ openModal, closeModal });
</script>
<style scoped>
.modal-backdrop {
position: fixed;
top: 0; left: 0; right: 0; bottom: 0;
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;
min-width: 300px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
</style>
// App.vue (or any parent component)
<template>
<div>
<h1>My App</h1>
<button @click="modalRef.openModal()">Open Modal</button>
<ModalComponent ref="modalRef" title="Important Message">
<p>This is dynamic content for the modal!</p>
</ModalComponent>
</div>
</template>
<script setup>
import { ref } from 'vue';
import ModalComponent from './ModalComponent.vue';
const modalRef = ref(null);
</script>
How it works: Vue 3's `<teleport>` component allows you to render a portion of your component's template into a DOM node that exists outside the hierarchy of that component. This is incredibly useful for modals, notifications, and tooltips, ensuring they render correctly at the root of the body or a specific container, preventing z-index or styling issues from parent components. The example shows a `ModalComponent` using `<teleport to="#modal-root">` to move its content to a designated DOM element, allowing for proper overlay behavior.