JAVASCRIPT
Render Content Outside Parent Component with Vue 3 Teleport
Master Vue 3's `Teleport` feature to render components like modals or notifications directly into the document body, bypassing parent DOM restrictions.
// components/ModalComponent.vue
<template>
<teleport to="body">
<div v-if="isOpen" class="modal-backdrop" @click="closeModal"></div>
<div v-if="isOpen" class="modal-container">
<div class="modal-header">
<h3>{{ title }}</h3>
<button @click="closeModal">X</button>
</div>
<div class="modal-body">
<slot>Default modal content</slot>
</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; right: 0; bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
z-index: 999;
}
.modal-container {
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;
width: 90%;
max-width: 500px;
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
}
.modal-header h3 {
margin: 0;
}
</style>
// Usage in a parent component (e.g., App.vue)
// <template>
// <div>
// <button @click="showModal = true">Open Modal</button>
// <ModalComponent v-model:isOpen="showModal" title="Important Message">
// <p>This is the content of the modal, rendered in the body!</p>
// </ModalComponent>
// </div>
// </template>
// <script setup>
// import { ref } from 'vue';
// import ModalComponent from './components/ModalComponent.vue';
// const showModal = ref(false);
// </script>
How it works: This snippet demonstrates Vue 3's `Teleport` feature, which allows you to render a component's content into a different part of the DOM tree, outside of its parent component. Here, a `ModalComponent` uses `<teleport to="body">` to render its backdrop and container elements directly into the `<body>` tag. This is incredibly useful for modals, notifications, or tooltips, ensuring they are not constrained by parent component's styling (like `overflow: hidden`) or z-index stacking contexts. The modal's visibility is controlled via a `v-model` pattern for `isOpen`.