JAVASCRIPT

Teleporting Modal Content Outside Component Hierarchy

Efficiently render modal dialogs, tooltips, or notifications outside the current component's DOM structure using Vue 3's Teleport feature for better layout control.

// ModalComponent.vue
<template>
  <teleport to="#modal-root">
    <div v-if="isOpen" class="modal-backdrop" @click.self="closeModal">
      <div class="modal-content">
        <h2>{{ title }}</h2>
        <p><slot>Default modal content.</slot></p>
        <button @click="closeModal">Close</button>
      </div>
    </div>
  </teleport>
</template>

<script setup>
import { defineProps, defineEmits } from 'vue';

const props = defineProps({
  isOpen: Boolean,
  title: String
});

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);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  max-width: 500px;
  width: 90%;
}
</style>

// App.vue (or parent component)
<template>
  <div>
    <h1>My App</h1>
    <button @click="showModal = true">Open Modal</button>

    <ModalComponent 
      :isOpen="showModal"
      title="Important Message"
      @close="showModal = false"
    >
      <p>This is the content slot for the modal.</p>
      <p>It will appear at the end of the body.</p>
    </ModalComponent>
  </div>
  <div id="modal-root"></div> <!-- Target element for Teleport -->
</template>

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

const showModal = ref(false);
</script>
How it works: This snippet demonstrates using Vue 3's `<Teleport>` component to render a modal dialog outside its parent component's DOM hierarchy. By specifying a `to` target (e.g., `#modal-root`), the modal's content is moved directly to that element in the main `index.html` (or any specified target element), solving common z-index and overflow issues. The modal's visibility is controlled by a reactive `isOpen` prop, and slots are used to inject dynamic content. This keeps the modal component encapsulated while allowing its output to appear correctly at a higher-level DOM node.

Need help integrating this into your project?

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

Hire DigitalCodeLabs