JAVASCRIPT
Creating Modals and Notifications with Vue 3 Teleport
Learn to use Vue 3's `Teleport` feature to render components like modals, tooltips, or notifications outside the normal DOM hierarchy, ensuring they always appear on top.
<!-- public/index.html (add a target div) -->
<!--
<div id="app"></div>
<div id="modals-container"></div>
-->
<!-- src/components/MyModal.vue -->
<template>
<Teleport to="#modals-container">
<div v-if="isOpen" class="modal-backdrop" @click="closeModal">
<div class="modal-content" @click.stop>
<h3>{{ title }}</h3>
<p><slot>Default modal content.</slot></p>
<button @click="closeModal">Close</button>
</div>
</div>
</Teleport>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps({
isOpen: Boolean,
title: String
});
const emit = defineEmits(['update:isOpen']);
const closeModal = () => {
emit('update:isOpen', false);
};
</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;
min-width: 300px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
z-index: 1001;
}
</style>
<!-- src/App.vue (or parent component) -->
<template>
<div>
<h1>Teleport Example</h1>
<button @click="isModalOpen = true">Open Modal</button>
<MyModal v-model:is-open="isModalOpen" title="Important Notice">
<p>This modal is rendered in a different DOM location!</p>
<p>It uses `Teleport` to avoid z-index or overflow issues from parent components.</p>
</MyModal>
<div style="height: 1000px; background: lightblue; padding: 20px; margin-top: 20px;">
<p>This is some other content.</p>
<p>Scroll down to see if the modal is affected by this parent's styling (it shouldn't be!).</p>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
import MyModal from './components/MyModal.vue';
const isModalOpen = ref(false);
</script>
How it works: Vue 3's `Teleport` component allows you to render a component's content into a different DOM node that exists outside the current component's hierarchy. This is incredibly useful for elements like modals, notifications, or tooltips that need to break out of their parent's styling or z-index context to appear on top of everything. By specifying a `to` target (e.g., an ID of a global div in `index.html`), `Teleport` ensures your component's content is always rendered where it needs to be, simplifying complex layout and styling challenges.