JAVASCRIPT
Use Vue 3 Teleport to Render Content Outside Component Hierarchy
Learn how to use Vue 3's built-in Teleport feature to render modal dialogs, tooltips, or notifications anywhere in the DOM, independent of their component's hierarchy.
// public/index.html (add a target div for teleported content)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vue Teleport Demo</title>
</head>
<body>
<div id="app"></div>
<div id="modal-root"></div> <!-- Target for Teleport -->
<script type="module" src="/src/main.js"></script>
</body>
</html>
// src/components/ModalComponent.vue
<template>
<Teleport to="#modal-root">
<div v-if="isOpen" class="modal-overlay">
<div class="modal-content">
<h3>{{ title }}</h3>
<p>{{ message }}</p>
<button @click="$emit('close')">Close</button>
</div>
</div>
</Teleport>
</template>
<script setup>
defineProps({
isOpen: {
type: Boolean,
default: false
},
title: {
type: String,
default: 'Modal Title'
},
message: {
type: String,
default: 'This is the modal content.'
}
});
defineEmits(['close']);
</script>
<style scoped>
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: 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 2px 10px rgba(0, 0, 0, 0.1);
text-align: center;
min-width: 300px;
}
</style>
// src/App.vue
<template>
<h1>Teleport Demo</h1>
<button @click="showModal = true">Open Modal</button>
<ModalComponent
:isOpen="showModal"
title="Important Notification"
message="This modal is rendered outside the #app div!"
@close="showModal = false"
/>
</template>
<script setup>
import { ref } from 'vue';
import ModalComponent from './components/ModalComponent.vue';
const showModal = ref(false);
</script>
How it works: This code demonstrates Vue 3's `Teleport` component for rendering content, like a modal, into a different part of the DOM tree. By targeting `#modal-root` (a div outside of `#app` in `index.html`), the `ModalComponent`'s content is visually displayed there, even though it's logically part of `App.vue`. This is invaluable for modals, tooltips, or notifications that need to escape component styling or DOM hierarchy to ensure correct layering and positioning.