头图

Vue3 teleport official document address: https://vuejs.org/guide/built-ins/teleport.html

The teleport API in Vue3 greatly facilitates the operation of the mobile Dom position in the Vue3 business logic.

Simple example

 <script setup lang="ts">
    // 控制节点
    let teleportToTarget = ref<string>('#idtest');
</script>
<template>
    <div id="idTest">id节点1</div>
    <div class="main">main节点1</div>
    <div class="main">main节点2</div>
    
    <teleport  :to="teleportToTarget">
        <div>传送节点</div>
    </teleport>
</template>

1. When teleportToTarget is #idTest, the node will be transferred to the #idTest node, which is equivalent to

 // let teleportToTarget = ref<string>('#idtest');
<template>
    <div id="idTest">
        id节点1<div>传送节点</div>
    </div>
    <div class="main">main节点1</div>
    <div class="main">main节点2</div>
</template>

2. When teleportToTarget is .main, the node will be transferred to the .main node. Multiple classes with the same name will be transferred to the first node by default. Equivalent to

 // let teleportToTarget = ref<string>('.main');
<template>
    <div id="idTest">id节点1</div>
    <div class="main">
        main节点1
        <div>传送节点</div>
    </div>
    <div class="main">main节点2</div>
</template>

3. When teleportToTarget is body, the node will be transferred to the end of the body node of the html element.

 // let teleportToTarget = ref<string>('body');

image.png

4. Delete the node

If you need to delete the node dynamically, you only need to use v-if to dynamically control the existence of the node, and the dom node will dynamically follow the teleportToTargetShow boolean value to dynamically exist.

 <script setup lang="ts">
    // 控制节点
    let teleportToTarget = ref<string>('#idtest');
    // 控制传输节点是否存在
    let teleportToTargetShow = ref<boolean>(true);
</script>
<teleport v-if="teleportToTargetShow" :to="teleportToTarget">
   <div>传送节点</div>
</teleport>

天渺工作室
69 声望3 粉丝

陕西人 目前在广东 设计师+全栈工程师+业余音乐制作人