← Back to all snippets
JAVASCRIPT

Vue 3 Teleport for Modals and Global Overlays

Understand Vue 3's Teleport feature to render a component's content in a different part of the DOM, ideal for modals, notifications, or tooltips that need to break out of parent styling.

// components/AppModal.vue
<template>
  <teleport to="#modal-root">
    <div v-if="show" class="modal-overlay" @click.self="close">
      <div class="modal-content">
        <slot></slot>
        <button @click="close">Close</button>
      </div>
    </div>
  </teleport>
</template>

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

const props = defineProps({
  show: Boolean
});

const emit = defineEmits(['close']);

function close() {
  emit('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;
  min-width: 300px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}
</style>

// index.html (ensure this element exists in your public/index.html)
<!-- ... other html ... -->
<div id="app"></div>
<div id="modal-root"></div>

// App.vue
<template>
  <div>
    <h1>My Application</h1>
    <button @click="isModalOpen = true">Open Modal</button>
    <AppModal :show="isModalOpen" @close="isModalOpen = false">
      <h2>Hello from the Modal!</h2>
      <p>This content is rendered outside the normal Vue app mounting point.</p>
    </AppModal>
  </div>
</template>

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

const isModalOpen = ref(false);
</script>
How it works: This snippet showcases Vue 3's `Teleport` component, perfect for rendering content like modals or notifications outside of the current component's DOM tree. The `AppModal` component uses `<teleport to="#modal-root">` to move its content to a specific target DOM element (a `div` with `id="modal-root"` in `index.html`). This ensures the modal overlay can cover the entire screen and avoid z-index or styling conflicts with parent components, even though its logical place is within `App.vue`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs