JAVASCRIPT

Render Modals and Overlays Outside Component Tree with Vue 3 Teleport

Discover how Vue 3's `<Teleport>` component allows you to render content into a different part of the DOM, perfect for accessible modals, tooltips, and notifications.

<!-- ModalComponent.vue -->
<template>
  <Teleport to="body">
    <div v-if="isOpen" class="modal-overlay" @click.self="$emit('close')">
      <div class="modal-content">
        <h3>Modal Title</h3>
        <p>This content is rendered globally, even if the modal component is deeply nested.</p>
        <button @click="$emit('close')">Close Modal</button>
      </div>
    </div>
  </Teleport>
</template>

<script setup>
const props = defineProps({
  isOpen: Boolean,
});
const emit = defineEmits(['close']);
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  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);
  max-width: 500px;
  width: 90%;
}
</style>

<!-- App.vue (or any parent component) -->
<template>
  <div>
    <h1>My Application</h1>
    <button @click="showModal = true">Open Modal</button>
    <ModalComponent :isOpen="showModal" @close="showModal = false" />
    <p style="margin-top: 100px;">Some other content on the page.</p>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import ModalComponent from './ModalComponent.vue';

const showModal = ref(false);
</script>
How it works: Vue 3's `<Teleport>` component allows you to move a part of your component's template into a different DOM node that exists outside the current component's hierarchy. This is incredibly useful for managing modals, notifications, or tooltips to avoid styling issues related to z-index, `overflow: hidden`, or parent element styling constraints. By teleporting to `body`, the modal's content is rendered directly under the `<body>` tag, simplifying its positioning and overlay behavior.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs