JAVASCRIPT
Manage DOM Positioning with Vue 3's `Teleport` Component
Learn to use Vue 3's built-in `Teleport` component to render content, such as modals or notifications, into a different part of the DOM tree.
// src/components/MyModal.vue
<template>
<teleport to="body">
<div v-if="isOpen" class="modal-backdrop" @click="closeModal"></div>
<div v-if="isOpen" class="modal-content">
<h2>Modal Title</h2>
<p>This content is teleported to the body!</p>
<slot></slot>
<button @click="closeModal">Close</button>
</div>
</teleport>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps({
isOpen: Boolean
});
const emit = defineEmits(['close']);
const closeModal = () => {
emit('close');
};
</script>
<style scoped>
.modal-backdrop {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
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;
max-width: 500px;
width: 90%;
}
</style>
// src/App.vue
<template>
<div>
<h1>Teleport Example</h1>
<button @click="showModal = true">Open Modal</button>
<MyModal :isOpen="showModal" @close="showModal = false">
<p>This is dynamic content passed through a slot.</p>
</MyModal>
<p>Some other content in the app...</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
import MyModal from './components/MyModal.vue';
const showModal = ref(false);
</script>
How it works: This snippet showcases the `Teleport` component, a built-in Vue 3 feature that allows you to render a part of your component's template into a different DOM node that exists outside the current component's DOM hierarchy. Here, a `MyModal` component uses `<teleport to="body">` to render its modal overlay and content directly into the `body` tag, preventing CSS stacking context or z-index issues from parent components.