JAVASCRIPT

Implement Modals and Notifications with Vue 3 Teleport

Learn how to use Vue 3's built-in `Teleport` component to render content (like modals, tooltips, or notifications) into a different part of the DOM tree.

// src/App.vue
<template>
  <div>
    <h1>My App Content</h1>
    <button @click="showModal = true">Open Modal</button>

    <Teleport to="#modal-target">
      <div v-if="showModal" class="modal-overlay" @click.self="showModal = false">
        <div class="modal-content">
          <h2>My Modal Title</h2>
          <p>This content is teleported to another part of the DOM!</p>
          <button @click="showModal = false">Close Modal</button>
        </div>
      </div>
    </Teleport>
  </div>
</template>

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

const showModal = ref(false);
</script>

<style>
/* Add some basic styling for the modal */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  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);
}
</style>

<!-- Public/index.html body or similar where #modal-target exists -->
<body>
  <div id="app"></div>
  <div id="modal-target"></div>
</body>
How it works: This snippet demonstrates how to use Vue 3's `Teleport` component. It allows rendering a portion of a component's template into a different DOM node that exists outside the current component's hierarchy. This is particularly useful for modals, notifications, or tooltips where you want the element to be appended directly to `body` (or a specific target) to avoid z-index or overflow issues from parent components.

Need help integrating this into your project?

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

Hire DigitalCodeLabs