JAVASCRIPT

Vue 3 Modals and Overlays with Teleport Feature

Learn to build accessible and cleanly structured modal components in Vue 3 using the `<Teleport>` feature, moving modal content to the document body.

// components/ModalDialog.vue
<template>
  <Teleport to="body">
    <div v-if="show" class="modal-overlay" @click.self="closeModal">
      <div class="modal-content">
        <button class="modal-close" @click="closeModal">X</button>
        <slot></slot>
      </div>
    </div>
  </Teleport>
</template>

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

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

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

function closeModal() {
  emit('close');
}

// Optional: Add/remove 'modal-open' class to body to prevent scrolling
watch(() => props.show, (newValue) => {
  if (newValue) {
    document.body.classList.add('modal-open');
  } else {
    document.body.classList.remove('modal-open');
  }
}, { immediate: true });
</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);
  position: relative;
  max-width: 500px;
  width: 90%;
}

.modal-close {
  position: absolute;
  top: 10px;
  right: 10px;
  border: none;
  background: none;
  font-size: 1.2em;
  cursor: pointer;
}
</style>

// App.vue (or any parent component)
<template>
  <div>
    <button @click="showModal = true">Open Modal</button>
    <ModalDialog :show="showModal" @close="showModal = false">
      <h2>Modal Title</h2>
      <p>This content is inside the modal.</p>
    </ModalDialog>
  </div>
</template>

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

const showModal = ref(false);
</script>
How it works: This snippet demonstrates creating a modal component using Vue 3's `<Teleport>` feature. Teleport allows the modal content to be rendered directly into a specified target element (like `body`) in the DOM, regardless of where the `ModalDialog` component is declared in the component tree. This prevents common z-index and styling issues, ensuring the modal always appears on top of other content. The `show` prop controls visibility, and the `close` event manages the modal's state.

Need help integrating this into your project?

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

Hire DigitalCodeLabs