JAVASCRIPT
Building a Reusable Modal with Teleport and Scoped Slots
Create a robust and accessible modal component in Vue 3 using the Teleport feature to render content anywhere in the DOM, combined with powerful scoped slots for flexible content customization.
// components/AppModal.vue
<template>
<teleport to="body">
<div v-if="modelValue" class="modal-backdrop" @click.self="closeModal">
<div class="modal-container">
<header class="modal-header">
<slot name="header">Default Header</slot>
<button class="modal-close-button" @click="closeModal">×</button>
</header>
<div class="modal-body">
<slot :message="'Hello from Modal'">Default Body</slot>
</div>
<footer class="modal-footer">
<slot name="footer"></slot>
<button @click="closeModal">Close</button>
</footer>
</div>
</div>
</teleport>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue'
const props = defineProps({
modelValue: Boolean
})
const emit = defineEmits(['update:modelValue'])
const closeModal = () => {
emit('update:modelValue', false)
}
</script>
<style scoped>
.modal-backdrop {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.7);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.modal-container {
background: white;
border-radius: 8px;
padding: 20px;
min-width: 300px;
max-width: 80%;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
font-size: 1.2em;
font-weight: bold;
}
.modal-close-button {
background: none;
border: none;
font-size: 1.5em;
cursor: pointer;
}
.modal-footer {
margin-top: 20px;
text-align: right;
}
</style>
// components/MyPage.vue
<template>
<div>
<h1>My Page</h1>
<button @click="showModal = true">Open Modal</button>
<AppModal v-model="showModal">
<template #header><h3>Custom Modal Title</h3></template>
<template #default="slotProps">
<p>This is the custom body content for the modal.</p>
<p>Message from modal: {{ slotProps.message }}</p>
</template>
<template #footer>
<button @click="doSomethingAndClose">Save Changes</button>
</template>
</AppModal>
</div>
</template>
<script setup>
import { ref } from 'vue'
import AppModal from './AppModal.vue'
const showModal = ref(false)
const doSomethingAndClose = () => {
alert('Saving changes...')
showModal.value = false
}
</script>
How it works: This snippet demonstrates building a flexible and reusable modal component using Vue 3's `Teleport` and `Slots`. `Teleport` ensures the modal content is rendered directly into the `body` tag, preventing z-index issues and ensuring it's outside the component's normal DOM hierarchy. The component utilizes named slots (`#header`, `#footer`) and a default slot (which is also a scoped slot, exposing `slotProps`) to allow consuming components to inject custom content for different parts of the modal, making it highly customizable. The `v-model` pattern manages the modal's visibility.