JAVASCRIPT

Vue 3 Teleport for Off-Hierarchy Content (e.g., Modals)

Master Vue 3's Teleport feature to render modals, notifications, or tooltips outside your component's DOM structure, enhancing accessibility and styling flexibility.

// components/AppModal.vue
<template>
  <teleport to="body">
    <div v-if="isOpen" class="modal-backdrop" @click="closeModal">
      <div class="modal-content" @click.stop>
        <h2>{{ title }}</h2>
        <p><slot>Default modal content.</slot></p>
        <button @click="closeModal">Close</button>
      </div>
    </div>
  </teleport>
</template>

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

const props = defineProps({
  isOpen: Boolean,
  title: String,
});

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

function closeModal() {
  emit('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: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  max-width: 500px;
  width: 90%;
}
</style>

// App.vue (Parent Component)
<template>
  <div>
    <h1>My Application</h1>
    <button @click="showModal = true">Open Modal</button>

    <AppModal :is-open="showModal" title="Welcome!" @close="showModal = false">
      <p>This content is rendered inside the modal, but the modal itself is teleported to the body!</p>
      <p>Enjoy the show!</p>
    </AppModal>

    <p style="margin-top: 20px;">Some other content on the page.</p>
  </div>
</template>

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

const showModal = ref(false);
</script>
How it works: This snippet demonstrates Vue 3's `Teleport` feature, which allows you to render a component's content into a different part of the DOM, outside its parent component's hierarchy. Here, an `AppModal` component uses `<teleport to="body">` to render its modal content directly into the `<body>` element. This is incredibly useful for managing modals, notifications, or tooltips, preventing z-index issues or styling conflicts with deeply nested components, and making it easier to ensure they are rendered above all other content on the page.

Need help integrating this into your project?

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

Hire DigitalCodeLabs