← Back to all snippets
JAVASCRIPT

Teleporting DOM Content for Modals/Overlays

Use Vue 3's <Teleport> component to render a component's content into a different DOM node, perfect for creating modals, tooltips, or notifications that break out of parent component styling.

// src/components/MyModal.vue
<template>
  <Teleport to="body">
    <div v-if="show" class="modal-backdrop" @click="$emit('close')">
      <div class="modal-content" @click.stop>
        <h3>Modal Title</h3>
        <p>This is the content of the modal, teleported to the body!</p>
        <slot></slot>
        <button @click="$emit('close')">Close</button>
      </div>
    </div>
  </Teleport>
</template>

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

defineProps({
  show: Boolean,
});

defineEmits(['close']);
</script>

<style scoped>
.modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  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%;
  text-align: center;
}
</style>

// src/App.vue
<template>
  <div>
    <h1>My App</h1>
    <p>Some content in the main app.</p>
    <button @click="showModal = true">Open Modal</button>

    <MyModal :show="showModal" @close="showModal = false">
      <p>This slot content is also teleported.</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 Vue 3's `<Teleport>` component, which allows you to render a portion of your component's template into a different DOM location, even outside its parent component's DOM tree. Here, a `MyModal` component uses `<Teleport to="body">` to ensure its modal backdrop and content are appended directly to the `<body>` tag. This is particularly useful for modals, notifications, or tooltips that need to break free from parent component's `overflow` or `z-index` styles, guaranteeing they always appear on top and are positioned correctly. The modal's visibility is controlled by the `show` prop, and an emit event `close` handles its closure.

Need help integrating this into your project?

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

Hire DigitalCodeLabs