JAVASCRIPT

Move DOM Content with Vue 3 Teleport

Learn how to use Vue 3's built-in Teleport feature to render component content into a different DOM location, perfect for modals, tooltips, and notifications.

// App.vue
<template>
  <div>
    <h1>My App</h1>
    <button @click="showModal = true">Open Modal</button>
    <MyModal :isVisible="showModal" @close="showModal = false" />
  </div>
</template>

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

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

// components/MyModal.vue
<template>
  <teleport to="body">
    <div v-if="isVisible" class="modal-backdrop" @click.self="$emit('close')">
      <div class="modal-content">
        <h2>Modal Title</h2>
        <p>This content is teleported to the body!</p>
        <button @click="$emit('close')">Close</button>
      </div>
    </div>
  </teleport>
</template>

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

const props = defineProps({
  isVisible: Boolean
});

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

<style scoped>
.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 allows you to render a component's content at a specific target location in the DOM, even if the component itself is nested deep within the Vue component tree. This is particularly useful for modals, tooltips, or notifications that need to break out of their parent's styling or z-index context and attach directly to `<body>` or another global element. The `to` prop specifies the target DOM element using a CSS selector or an actual DOM node.

Need help integrating this into your project?

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

Hire DigitalCodeLabs