JAVASCRIPT
Vue 3 Teleport for Modals and Overlays
Use Vue 3's built-in Teleport component to render modals, tooltips, or notifications outside their parent component's DOM hierarchy for cleaner structure.
// components/Modal.vue
<template>
<teleport to="body">
<div v-if="isVisible" class="modal-backdrop" @click="closeModal"></div>
<div v-if="isVisible" class="modal-content">
<h3>Modal Title</h3>
<p>This content is rendered outside its parent component's DOM tree.</p>
<slot></slot>
<button @click="closeModal">Close</button>
</div>
</teleport>
</template>
<script setup>
import { ref } from 'vue';
const isVisible = ref(false);
const openModal = () => { isVisible.value = true; };
const closeModal = () => { isVisible.value = false; };
// Expose functions for parent to control modal visibility
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);
z-index: 999;
}
.modal-content {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
z-index: 1000;
width: 80%;
max-width: 500px;
}
</style>
// App.vue
<template>
<div>
<h1>Teleport Example</h1>
<p>This paragraph is within the App component.</p>
<button @click="modalRef.openModal()">Open Modal</button>
<Modal ref="modalRef">
<p>This is slot content passed to the modal.</p>
</Modal>
</div>
</template>
<script setup>
import { ref } from 'vue';
import Modal from './components/Modal.vue';
const modalRef = ref(null);
</script>
How it works: The Vue 3 `<Teleport>` component allows you to render a portion of your component's template into a different DOM node that exists outside the component's own DOM hierarchy. This is incredibly useful for managing modals, tooltips, notifications, or any overlay, as it prevents styling issues and z-index conflicts by placing them directly into the `body` or another designated target. The example shows a modal component whose content is 'teleported' to the `<body>` element.