Vue 3 Teleport for Modals and Toasts

Vue 3 Teleport for Modals and Toasts

Vue 3 Teleport for Modals and Toasts

<Teleport> moves its slot content to a different part of the DOM at render time — solving z-index and overflow issues for overlays.

<!-- Modal.vue -->
<script setup>
defineProps({ show: Boolean })
defineEmits(['close'])
</script>

<template>
  <Teleport to="body">
    <Transition name="modal">
      <div v-if="show" class="overlay" @click.self="$emit('close')">
        <div class="modal-box">
          <slot />
          <button @click="$emit('close')">Close</button>
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

<style scoped>
.overlay  { position: fixed; inset: 0; background: rgba(0,0,0,.5); display: grid; place-items: center; }
.modal-box { background: white; border-radius: 8px; padding: 2rem; min-width: 320px; }
.modal-enter-active, .modal-leave-active { transition: opacity .2s; }
.modal-enter-from, .modal-leave-to       { opacity: 0; }
</style>
<!-- Usage anywhere in the tree -->
<Modal :show="isOpen" @close="isOpen = false">
  <h2>Confirm Delete</h2>
  <p>This action cannot be undone.</p>
</Modal>
All Comments