JAVASCRIPT
Render Content Anywhere with Vue 3 Teleport
Learn to use Vue 3's `Teleport` component to render content (like modals or tooltips) into a different DOM location, outside its parent component's hierarchy, preventing common styling issues.
// Modal.vue
<template>
<teleport to="body">
<div v-if="isOpen" class="modal-overlay">
<div class="modal-content">
<slot></slot>
<button @click="$emit('close')">Close</button>
</div>
</div>
</teleport>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
defineProps({
isOpen: {
type: Boolean,
default: false
}
});
defineEmits(['close']);
</script>
<style>
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
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);
}
</style>
// App.vue (example usage)
<template>
<div>
<h1>My App Content</h1>
<button @click="showModal = true">Open Modal</button>
<Modal :is-open="showModal" @close="showModal = false">
<h2>Hello from the Modal!</h2>
<p>This content is rendered directly into the body.</p>
</Modal>
</div>
</template>
<script setup>
import { ref } from 'vue';
import Modal from './Modal.vue';
const showModal = ref(false);
</script>
How it works: The `Teleport` component allows rendering part of a component's template into a different DOM node that exists outside the component's own DOM hierarchy. In this example, `Modal.vue` uses `<teleport to="body">` to render its content directly into the `<body>` element. This is crucial for elements like modals or tooltips to avoid styling issues and z-index conflicts caused by parent component's overflow or positioning.