JAVASCRIPT

Render Modals and Overlays with Vue 3 Teleport

Master the Vue 3 Teleport component to render content outside your component's DOM hierarchy, perfect for accessible modals, tooltips, and notifications.

// ModalComponent.vue
<template>
  <teleport to="body"> <!-- Teleports the modal content directly into the body -->
    <div v-if="isOpen" class="modal-backdrop" @click.self="closeModal">
      <div class="modal-content">
        <h2>{{ title }}</h2>
        <p>This is the content of the modal. It appears outside its parent component's DOM tree.</p>
        <slot></slot>
        <button @click="closeModal">Close</button>
      </div>
    </div>
  </teleport>
</template>

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

const props = defineProps({
  isOpen: {
    type: Boolean,
    required: true,
  },
  title: {
    type: String,
    default: 'Modal Title',
  },
});

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

const closeModal = () => {
  emit('close');
};
</script>

<style scoped>
/* Basic styling for the modal */
.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%;
}
</style>

// App.vue
<template>
  <div>
    <h1>My App</h1>
    <p>Welcome to the main application content.</p>
    <button @click="isModalOpen = true">Open Modal</button>

    <ModalComponent :is-open="isModalOpen" title="Important Notice" @close="isModalOpen = false">
      <p>You can pass custom content into the modal via slots!</p>
    </ModalComponent>
  </div>
</template>

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

const isModalOpen = ref(false);
</script>
How it works: The Vue 3 `Teleport` component allows you to render a part of your component's template into a different location in the DOM, even outside the current component's hierarchy. This is incredibly useful for modals, tooltips, notifications, or any elements that need to break free from their parent's styling or z-index constraints. Here, `ModalComponent` uses `<teleport to="body">` to ensure the modal always appears directly under the `<body>` tag, simplifying overlay management.

Need help integrating this into your project?

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

Hire DigitalCodeLabs