JAVASCRIPT
Render Modals or Notifications Anywhere with Vue 3 Teleport
Master Vue 3's Teleport component to render child components into a different DOM location, perfect for creating accessible modals, tooltips, or notifications.
// App.vue (or any root component where #teleport-target exists)
// <template>
// <div id="app">
// <button @click="showModal = true">Open Modal</button>
// <MyModal v-if="showModal" @close="showModal = false" />
// <div id="teleport-target"></div> <!-- Target element for teleported content -->
// </div>
// </template>
//
// <script setup>
// import { ref } from 'vue';
// import MyModal from './components/MyModal.vue';
//
// const showModal = ref(false);
// </script>
// components/MyModal.vue
// <template>
// <teleport to="#teleport-target">
// <div class="modal-backdrop" @click.self="$emit('close')">
// <div class="modal-content">
// <h2>This is a Teleported Modal</h2>
// <p>I am rendered outside the component's parent DOM hierarchy.</p>
// <button @click="$emit('close')">Close Modal</button>
// </div>
// </div>
// </teleport>
// </template>
//
// <script setup>
// import { defineEmits } from 'vue';
//
// 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: white;
// padding: 20px;
// border-radius: 8px;
// box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
// z-index: 1001;
// }
// </style>
How it works: This snippet illustrates Vue 3's `Teleport` component, which allows a component's content to be rendered into a different part of the DOM tree, outside of its parent's logical hierarchy. This is incredibly useful for creating modals, tooltips, or notifications that need to sit at the top level of the DOM (e.g., directly under `<body>`) to avoid styling conflicts or z-index issues from parent components, while still maintaining reactivity and data flow with its original parent.