← Back to all snippets
JAVASCRIPT

Vue 3 Teleport Component for Modals and Overlays

Understand how to use Vue 3's built-in <Teleport> component to render a part of your component's template into a different DOM node, perfect for modals, tooltips, or notifications.

// public/index.html (or equivalent, add a target div)
<!-- ... other HTML ... -->
<body>
  <div id="app"></div>
  <div id="modals-target"></div> <!-- Our teleport target -->
</body>
<!-- ... -->

// src/components/MyModal.vue
<template>
  <teleport to="#modals-target">
    <div v-if="isOpen" class="modal-overlay" @click.self="$emit('close')">
      <div class="modal-content">
        <h2>{{ title }}</h2>
        <p><slot>Default modal content.</slot></p>
        <button @click="$emit('close')">Close</button>
      </div>
    </div>
  </teleport>
</template>

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

defineProps({
  isOpen: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: 'Modal Title'
  }
});

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: 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>My App</h1>
    <button @click="showModal = true">Open Modal</button>
    <MyModal :is-open="showModal" title="Important Notification" @close="showModal = false">
      <p>This is some content for the modal.</p>
      <p>It's rendered outside the app root!</p>
    </MyModal>
  </div>
</template>

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

const showModal = ref(false);
</script>
How it works: This snippet demonstrates the use of Vue 3's `<Teleport>` component to effectively manage modals. It shows how to define a target DOM element (`#modals-target` in `public/index.html`), and then use `<Teleport>` within a `MyModal` component to render its content directly into that target, regardless of where `MyModal` is placed in the component tree. This prevents common z-index issues and ensures modals are always rendered on top of other content.

Need help integrating this into your project?

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

Hire DigitalCodeLabs