← Back to all snippets
JAVASCRIPT

Managing DOM Placement with Vue 3 Teleport for Modals

Learn to use Vue 3's `Teleport` feature to render components like modals outside their parent component's DOM hierarchy, ensuring proper styling and stacking.

// src/components/MyModal.vue
<template>
  <Teleport to="body">
    <div v-if="isOpen" class="modal-overlay" @click.self="closeModal">
      <div class="modal-content">
        <h2>Modal Title</h2>
        <p>This is the content of the modal. It's teleported to the body!</p>
        <button @click="closeModal">Close Modal</button>
      </div>
    </div>
  </Teleport>
</template>

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

const isOpen = ref(false);

const openModal = () => {
  isOpen.value = true;
};

const closeModal = () => {
  isOpen.value = false;
};

// Expose functions to parent component
defineExpose({
  openModal,
  closeModal
});
</script>

<style scoped>
.modal-overlay {
  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);
  width: 80%;
  max-width: 500px;
}
</style>

// src/App.vue
<template>
  <div>
    <h1>Teleport Example</h1>
    <button @click="modalRef.openModal()">Open Teleported Modal</button>
    <MyModal ref="modalRef" />
  </div>
</template>

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

const modalRef = ref(null);
</script>
How it works: This snippet demonstrates Vue 3's `Teleport` feature, ideal for components like modals that need to render outside their parent's DOM tree (e.g., directly under `body`). The `<Teleport to="body">` tag ensures the modal's HTML is moved to the target element (`body` in this case), preventing z-index or overflow issues from parent components. The modal's visibility is managed by a reactive `isOpen` ref, and `defineExpose` makes its `openModal` and `closeModal` methods accessible to the parent component.

Need help integrating this into your project?

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

Hire DigitalCodeLabs