vue.js logo

Teleport Component for Modals and Pop-ups


Step 1: Create the Modal Component

Create a new Vue component that will serve as the modal. For instance, create a file named Modal.vue.


<template>
        <div class="modal-backdrop">
          <div class="modal-content">
            <slot></slot>
            <button @click="close">Close</button>
          </div>
        </div>
      </template>

      <script>
      export default {
        emits: ['close'],
        methods: {
          close() {
            this.$emit('close');
          }
        }
      }
      </script>

      <style>
      .modal-backdrop {
        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;
      }

      .modal-content {
        background: white;
        padding: 20px;
        border-radius: 5px;
      }
      </style>

Step 2: Use Teleport in the Main Component

Modify your main component, such as App.vue, to use the component and include the modal.


<template>
        <div>
          <button @click="showModal = true">Open Modal</button>
          <Teleport to="body">
            <Modal v-if="showModal" @close="showModal = false">
              <p>This is some content for the modal!</p>
            </Modal>
          </Teleport>
        </div>
      </template>

      <script>
      import Modal from './components/Modal.vue';

      export default {
        components: {
          Modal
        },
        data() {
          return {
            showModal: false
          };
        }
      }
      </script>

Conclusion

By using the Teleport component, you have successfully created a modal that renders directly inside the body tag, ensuring that it is free from any CSS constraints that might affect its appearance or functionality. This approach is particularly useful for full-screen overlays, modals, and even toast notifications, making your application's UI more robust and user-friendly.