Blog>
Snippets

Vue.js 3 Teleport Feature and Impact on VDOM

Clarify how to use the new teleport feature in Vue.js 3 to move parts of the component template to other parts of the DOM outside the current VDOM tree.
<template>
  <div>
    <teleport to="body">
      <div v-if="showModal" class="modal">
        <!-- Modal Content Here -->
        <p>This modal is teleported to the body tag!</p>
        <button @click="closeModal">Close</button>
      </div>
    </teleport>
  </div>
</template>

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

export default {
  setup() {
    const showModal = ref(false);

    function closeModal() {
      showModal.value = false;
    }

    // Simulate showing the modal
    setTimeout(() => {
      showModal.value = true;
    }, 1000);

    return {
      showModal,
      closeModal
    };
  }
};
</script>

<style>
.modal {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  padding: 20px;
  background-color: white;
  border: 1px solid #ccc;
  z-index: 1000;
}
</style>
This Vue.js component example uses the `teleport` feature to move a modal element to the `body` tag of the HTML document. When `showModal` becomes `true`, the modal is displayed and since it is teleported to the body tag, it will not be affected by the styling or layout of its original place in the Vue component.