← Back to all snippets
VUE

Using Vue 3 Teleport for Modals and Overlays

Learn to effectively use Vue 3's Teleport component to render modal dialogs, notifications, or tooltips outside of their parent component's DOM hierarchy.

<!-- Modal.vue -->
<template>
  <teleport to="body">
    <div v-if="isOpen" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <h2>Modal Title</h2>
        <p>This content is rendered outside the component's parent DOM element.</p>
        <button @click="closeModal">Close</button>
      </div>
    </div>
  </teleport>
</template>

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

const isOpen = ref(false);

const openModal = () => {
  isOpen.value = true;
};

const closeModal = () => {
  isOpen.value = false;
};

// Expose functions for parent components to control the modal
defineExpose({
  openModal,
  closeModal
});
</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: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  text-align: center;
}
</style>

<!-- App.vue (example usage) -->
<template>
  <div>
    <h1>My App Content</h1>
    <button @click="modalRef.openModal()">Open Modal</button>
    <Modal ref="modalRef" />
  </div>
</template>

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

const modalRef = ref(null);
</script>
How it works: Vue 3's `<Teleport>` component allows you to render a part of a component's template into a different location in the DOM, outside of its parent component's hierarchy. This is particularly useful for modals, notifications, or tooltips, ensuring they appear at the top level of the DOM (e.g., directly under `body`) to avoid z-index or styling issues from parent components. The `to` prop specifies the target DOM element.

Need help integrating this into your project?

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

Hire DigitalCodeLabs