JAVASCRIPT

Managing Modals and Overlays with Vue 3 Teleport

Use Vue 3's <Teleport> component to render modal windows or notifications outside the component's DOM hierarchy, ensuring proper layering and avoiding CSS z-index issues.

<template>
  <div>
    <h1>My Application</h1>
    <p>This is the main content of the app.</p>
    <button @click="isModalOpen = true">Open Modal</button>

    <Teleport to="body">
      <div v-if="isModalOpen" class="modal-backdrop" @click="isModalOpen = false">
        <div class="modal-content" @click.stop>
          <h2>Modal Title</h2>
          <p>This modal content is teleported to the body!</p>
          <button @click="isModalOpen = false">Close Modal</button>
        </div>
      </div>
    </Teleport>
  </div>
</template>

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

const isModalOpen = ref(false);
</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; /* Ensure it's above other content */
}

.modal-content {
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  text-align: center;
  color: #333;
}

button {
    padding: 10px 20px;
    margin-top: 15px;
    cursor: pointer;
    background-color: #42b983;
    color: white;
    border: none;
    border-radius: 5px;
}
</style>
How it works: This snippet demonstrates Vue 3's `<Teleport>` feature, which allows you to render a component's content into a different part of the DOM tree, even if that part is outside the component's mounting element. Here, a modal (`.modal-backdrop` and `.modal-content`) is defined within a `template` but is `teleport`-ed to the `<body>` element. This is especially useful for modals, notifications, or tooltips, ensuring they are rendered at the root of the DOM, preventing z-index conflicts and CSS overflow issues from parent components, and making them truly global.

Need help integrating this into your project?

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

Hire DigitalCodeLabs