JAVASCRIPT
Implementing a Modal with Vue 3 Teleport
Efficiently render modal dialogs, notifications, or tooltips outside their component hierarchy using Vue 3's built-in <Teleport> component for cleaner DOM structure.
// src/components/BaseModal.vue
<template>
<teleport to="body">
<div v-if="isOpen" class="modal-backdrop" @click.self="closeModal">
<div class="modal-content">
<slot></slot>
<button @click="closeModal">Close</button>
</div>
</div>
</teleport>
</template>
<script setup>
import { ref } from 'vue';
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;
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: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
min-width: 300px;
max-width: 80%;
z-index: 1001;
}
</style>
// src/App.vue
<template>
<div>
<h1>Welcome to My App</h1>
<button @click="modalRef.openModal()">Open Modal</button>
<BaseModal ref="modalRef">
<h2>Modal Title</h2>
<p>This content is rendered outside the app root!</p>
</BaseModal>
</div>
</template>
<script setup>
import { ref } from 'vue';
import BaseModal from './components/BaseModal.vue';
const modalRef = ref(null);
</script>
How it works: This snippet demonstrates how to create a modal using Vue 3's `Teleport` component. The `BaseModal.vue` component wraps its content in `<teleport to="body">`, which means the modal's backdrop and content will be rendered directly inside the `<body>` tag in the DOM, regardless of where `BaseModal` is placed in the component tree. This prevents CSS stacking context issues. The modal's visibility is controlled by an `isOpen` ref, and `defineExpose` is used to allow the parent component (`App.vue`) to open and close the modal programmatically via a template ref.