JAVASCRIPT
Teleporting Component Content to a Different DOM Location in Vue 3
Discover how Vue 3's `<Teleport>` component allows you to render a component's content into a different part of the DOM, perfect for modals, tooltips, and notifications.
// App.vue
<template>
<div>
<h1>App Component</h1>
<button @click="showModal = true">Open Modal</button>
<div id="modal-container">
<!-- This is where the teleported content will go -->
<p>Content below the modal, but not inside its structure.</p>
</div>
<!-- The Modal component, logically here, but rendered into #modal-container -->
<Modal :show="showModal" @close="showModal = false" />
</div>
</template>
<script setup>
import { ref } from 'vue';
import Modal from './components/Modal.vue';
const showModal = ref(false);
</script>
// components/Modal.vue
<template>
<Teleport to="#modal-container">
<div v-if="show" class="modal-backdrop" @click.self="$emit('close')">
<div class="modal-content">
<h2>My Teleported Modal</h2>
<p>This content is rendered outside its parent component's DOM structure.</p>
<button @click="$emit('close')">Close Modal</button>
</div>
</div>
</Teleport>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
defineProps({
show: Boolean,
});
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-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}
</style>
How it works: This snippet demonstrates Vue 3's `<Teleport>` component, which allows you to move a part of your component's template into a different DOM node that exists outside the current component's DOM hierarchy. In this example, the `Modal` component's content is logically defined within `App.vue`'s template structure, but `<Teleport to="#modal-container">` renders the modal's backdrop and content into the `<div id="modal-container">` element located directly within `App.vue`'s body. This is ideal for modals, notifications, or tooltips that need to break out of their parent's styling or z-index context.