JAVASCRIPT

Render Content Outside Parent with Teleport

Discover Vue 3's `Teleport` component to render a part of your component's template into a different DOM location, perfect for modals, tooltips, or notifications.

<template>
  <div class="app-container">
    <h1>Main Application Content</h1>
    <p>Click the button below to open a modal.</p>
    <button @click="showModal = true">Open Modal</button>

    <Teleport to="body">
      <div v-if="showModal" class="modal-backdrop" @click="showModal = false">
        <div class="modal-content" @click.stop>
          <h2>Modal Title</h2>
          <p>This content is rendered directly into the body!</p>
          <button @click="showModal = false">Close</button>
        </div>
      </div>
    </Teleport>
  </div>
</template>

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

const showModal = ref(false);
</script>

<style>
.modal-backdrop {
  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;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  z-index: 1001;
}
</style>
How it works: The `Teleport` component in Vue 3 allows you to move a portion of a component's template into a specified target DOM element, even if that target is outside the component's normal DOM hierarchy. This is incredibly useful for modals, dropdowns, or notifications that need to render directly under `<body>` to avoid CSS stacking issues or overflowing parent elements, while still maintaining reactivity and component logic within its original context.

Need help integrating this into your project?

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

Hire DigitalCodeLabs