Teleport

Teleport Vue 3.0 is one of the new features.

Teleport is a technology that can render our template to the specified DOM node, not affected by the parent style, V-show and other attributes, but data and prop data can still be shared. React Portal.

The sample

The Teleport tag contains the to attribute to specify the target DOM node to mount

  <template>
    <div class="hello">
      <span>Hello World</span>

      <teleport to="#teleport-target">
        <span>Hello Teleport</span>
      </teleport>
    </div>
  </template>
Copy the code
<script>
  export default {
    beforeCreate() {
      const node = document.createElement("div");
      node.id = "teleport-target";
      document.body.appendChild(node); }}; </script>Copy the code

As shown in figure:

style

Because the Teleport node is mounted under another specified DOM node, it is completely unaffected by the parent style

.hello span {
  color: red;
}
.hello {
  position: absolute;
  top: 0;
}
Copy the code

As shown in figure:

instruction

The parent cannot capture the event bubbling of the Teleport node, and most instructions except V-if cannot be applied to the Teleport node.

  <template>
    <div class="hello" @click="handle">
      <span>Hello World</span>

      <teleport to="#teleport-target">
        <span>Hello Teleport</span>
      </teleport>
    </div>
  </template>
Copy the code
<script>
  export default {
    methods: {
      handle(e) {
        console.log('click:,e.target.innerText)
      }
    }
  };
</script>
Copy the code

As shown in figure: