JAVASCRIPT

Use Teleport for Modals and Global Elements in Vue 3

Learn how to render component content into a different part of the DOM tree using Vue 3's <teleport> component, ideal for modals and notifications.

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

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

defineProps({
  isOpen: Boolean,
});
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: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  max-width: 500px;
  width: 90%;
}
</style>

// src/App.vue
<template>
  <div>
    <h1>App Content</h1>
    <button @click="isModalOpen = true">Open Modal</button>
    <MyModal :is-open="isModalOpen" @close="isModalOpen = false" />
  </div>
  <!-- This is the target for the teleported content -->
  <div id="modal-target"></div>
</template>

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

const isModalOpen = ref(false);
</script>
How it works: This snippet demonstrates Vue 3's `<teleport>` component, which allows you to render a component's template part into a different DOM node that exists outside the current component's hierarchy. This is particularly useful for managing global elements like modals, tooltips, or notifications, ensuring they are correctly positioned at the `<body>` level or another specific target, preventing CSS z-index or overflow issues from parent components. The `to` prop specifies a CSS selector or an actual DOM element as the target.

Need help integrating this into your project?

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

Hire DigitalCodeLabs