JAVASCRIPT
Teleport Modals and Overlays to the Body in Vue 3
Use Vue 3's built-in `<Teleport>` component to render content into a different DOM node, ideal for modals, tooltips, and floating elements.
// src/components/MyModal.vue
<template>
<Teleport to="body">
<div v-if="isOpen" class="modal-backdrop" @click.self="$emit('close')">
<div class="modal-content">
<h2>{{ title }}</h2>
<p><slot>Default modal content goes here.</slot></p>
<button @click="$emit('close')">Close Modal</button>
</div>
</div>
</Teleport>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
defineProps({
isOpen: {
type: Boolean,
default: false
},
title: {
type: String,
default: 'Modal Title'
}
});
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-content {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
max-width: 500px;
width: 90%;
text-align: center;
}
</style>
// src/App.vue
<template>
<div>
<h1>Teleport Example</h1>
<p>Click the button to open a modal that renders directly into the document body.</p>
<button @click="showModal = true">Open Modal</button>
<MyModal :is-open="showModal" @close="showModal = false" title="Important Notice">
<p>This modal content is being teleported!</p>
<p>It helps keep the modal outside of the app's DOM hierarchy for better styling and z-indexing.</p>
</MyModal>
</div>
</template>
<script setup>
import { ref } from 'vue';
import MyModal from './components/MyModal.vue';
const showModal = ref(false);
</script>
<style>
/* Basic app styles */
body { font-family: sans-serif; }
#app { padding: 20px; }
</style>
How it works: This snippet demonstrates Vue 3's `Teleport` component, which allows you to render a component's content into a different part of the DOM tree, even outside of its parent component's hierarchy. Here, a `MyModal` component uses `<Teleport to="body">` to render its entire content directly into the document's `<body>` element. This is especially useful for modals, tooltips, or notifications, as it prevents styling and z-index issues that might arise from being nested deep within the application's component tree.