JAVASCRIPT

Vue 3 Teleport for Rendering Modals Outside Component Tree

Utilize Vue 3's Teleport feature to render a modal or dialog component directly into the body, preventing z-index issues and ensuring proper overlay behavior regardless of component nesting.

<!-- ModalComponent.vue -->
<template>
  <teleport to="body">
    <div v-if="isVisible" class="modal-overlay" @click.self="closeModal">
      <div class="modal-content">
        <h3>{{ title }}</h3>
        <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({
  isVisible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: 'Modal Title',
  },
});

const emit = defineEmits(['close']);

const closeModal = () => {
  emit('close');
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  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%;
  text-align: center;
}
</style>

<!-- How to use in parent component: -->
<!-- <template>
  <div>
    <button @click="showModal = true">Open Modal</button>
    <ModalComponent :isVisible="showModal" @close="showModal = false" title="My Awesome Modal">
      <p>This is dynamic content passed via a slot!</p>
    </ModalComponent>
  </div>
</template>
<script setup>
import { ref } from 'vue';
import ModalComponent from './ModalComponent.vue';
const showModal = ref(false);
</script> -->
How it works: This snippet demonstrates `Teleport` in Vue 3, allowing a modal component to render its content directly into the `body` element of the HTML document, regardless of where `ModalComponent` is nested in the component tree. This prevents common CSS stacking context issues (`z-index`) and ensures the modal always appears on top of other content. The `v-if` conditionally renders the modal, and the `click.self` handler closes it when clicking the overlay.

Need help integrating this into your project?

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

Hire DigitalCodeLabs