Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This is the eighth article in this series on the portal component Teleport

Previous related articles can be moved:

  • Vue series: Vue3’s new composition API
  • The use of ref and Reactive functions in composition API in Vue3
  • [Vue series-3] About responsive deep listening and non-deep listening
  • [Vue3 series -4] toRaw and markRaw in Composition API
  • Do you know ref as well as toRef and toRefs
  • You may know ref, but do you know how to customize a ref
  • Do you know how to get DOM elements from the ref attribute in Vue3

Teleport, known as a portal component, is used to provide a concise way to specify the parent element of its contents

For example, define a modal box that is originally inside a component, but I want it to be under the body when it pops up, level with #app. The following code

<template>
  <button @click="modalsOpen = true">Popup button</button>
  <teleport to='body'>
    <div v-if="modalsOpen" class="modals">
      <div>
          <p>This is a pop-up box that is passed to the body</p>
          <button @click="modalsOpen = false">Shut down</button>
      </div>      
    </div>
  </teleport>
</template>

<script>
import { ref } from "vue";
export default {
  name: "Modals".setup() {
    let modalsOpen = ref(false);
    return{ modalsOpen }; }};</script>

<style scoped>
.modals{
    background-color: rgba(0.0.0.5);
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}
.modals div{
    border-radius: 4px;
    width: 300px;
    height: 100px;
    background-color:#fff;
    padding: 20px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    font-size:.9em;
    color:  rgba(0.0.0.9);
}
button{
    padding: 5px;
}
</style>
Copy the code

The following information is displayed:

We found that the Teleport component is also relatively simple to use, with the to attribute being the element selector to send its contents to the specified element