JAVASCRIPT
Building a Reusable Modal with Teleport and Slots in Vue 3
Create a flexible and accessible modal component in Vue 3 using `Teleport` to render content outside the app, and `slots` for customizable headers, body, and footers.
// components/BaseModal.vue
<template>
<teleport to="body">
<div v-if="isOpen" class="modal-backdrop" @click.self="$emit('close')">
<div class="modal-container">
<header class="modal-header">
<slot name="header">
<h3>Default Header</h3>
</slot>
<button class="modal-close-button" @click="$emit('close')">×</button>
</header>
<section class="modal-body">
<slot>
<p>Default Body Content</p>
</slot>
</section>
<footer class="modal-footer">
<slot name="footer">
<button @click="$emit('close')">Close</button>
</slot>
</footer>
</div>
</div>
</teleport>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps({
isOpen: {
type: Boolean,
required: true
}
});
const emit = defineEmits(['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-container {
background: white;
border-radius: 8px;
padding: 20px;
min-width: 300px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
position: relative;
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
border-bottom: 1px solid #eee;
padding-bottom: 10px;
}
.modal-close-button {
background: none;
border: none;
font-size: 1.5em;
cursor: pointer;
color: #666;
}
.modal-footer {
margin-top: 15px;
border-top: 1px solid #eee;
padding-top: 10px;
text-align: right;
}
</style>
// App.vue (example usage)
<template>
<button @click="isModalOpen = true">Open Modal</button>
<BaseModal :is-open="isModalOpen" @close="isModalOpen = false">
<template #header>
<h2>Custom Modal Title</h2>
</template>
<p>This is the custom body content of the modal.</p>
<template #footer>
<button @click="isModalOpen = false">Got it!</button>
</template>
</BaseModal>
</template>
<script setup>
import { ref } from 'vue';
import BaseModal from './components/BaseModal.vue';
const isModalOpen = ref(false);
</script>
How it works: This snippet demonstrates creating a flexible modal component in Vue 3. It utilizes `<Teleport to="body">` to render the modal's content directly into the document body, preventing z-index issues and ensuring proper overlay behavior, regardless of its parent component's styling. Named and default `<slot>` elements allow for customizable headers, footers, and main content, making the `BaseModal` component highly reusable across an application.