JAVASCRIPT

Creating Global Modals and Notifications with Vue 3 Teleport

Learn how to use Vue 3's `Teleport` feature to render component content into a different part of the DOM, perfect for modals, notifications, or tooltips.

// public/index.html (or similar root HTML file)
<!-- Ensure you have a target element for teleporting, e.g., before the closing </body> -->
<body>
  <div id="app"></div>
  <div id="modal-target"></div> <!-- This is our teleport target -->
</body>

// src/components/App.vue
<template>
  <div id="app-root">
    <h1>Main Application Content</h1>
    <p>This is the main application area.</p>
    <button @click="showModal = true">Open Modal</button>
    <MyModal :isVisible="showModal" @close="showModal = false" />
  </div>
</template>

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

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

<style>
#app-root { font-family: Avenir, Helvetica, Arial, sans-serif; text-align: center; color: #2c3e50; margin-top: 60px; }
</style>


// src/components/MyModal.vue
<template>
  <teleport to="#modal-target">
    <div v-if="isVisible" class="modal-overlay" @click.self="$emit('close')">
      <div class="modal-content">
        <h2>Modal Title</h2>
        <p>This modal content is rendered outside the component's parent DOM tree.</p>
        <button @click="$emit('close')">Close Modal</button>
      </div>
    </div>
  </teleport>
</template>

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

defineProps({
  isVisible: {
    type: Boolean,
    default: false,
  },
});

defineEmits(['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: 30px;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  max-width: 500px;
  width: 90%;
  text-align: center;
}

.modal-content button { margin-top: 20px; padding: 10px 20px; cursor: pointer; }
</style>
How it works: This snippet showcases Vue 3's `Teleport` component for rendering content into a different DOM element, independent of the component's parent. Here, `MyModal` is placed within `App.vue`, but its content is `teleported` to a designated `#modal-target` div in `public/index.html`. This is ideal for modals, tooltips, or notifications that need to break out of their parent's styling or z-index constraints.

Need help integrating this into your project?

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

Hire DigitalCodeLabs