4

Vue3中的teleport节点传送

 1 year ago
source link: https://www.fly63.com/article/detial/11784
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

更新日期: 2022-06-22阅读量: 6标签: 节点分享

扫一扫分享

vue3 teleport官方文档地址:https://vuejs.org/guide/built-ins/teleport.html

Vue3中的teleport api极大方便了在Vue3业务逻辑中操作移动dom位置。

<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.当teleportToTarget 为#idTest时,节点会被传输到 #idTest 节点中,等同于

// 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.当teleportToTarget 为.main时,节点会被传输到 .main时 节点中,多个class同名,默认会传输到第一个节点中。等同于

// 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.当teleportToTarget 为body时,节点会被传输到html元素的body节点末尾中。

// let teleportToTarget = ref<string>('body');
62b27b1994548.jpg

4.删除节点

需要动态删除节点,只需要用v-if动态控制节点存在,dom节点会动态跟随teleportToTargetShow布尔值动态是否存在。

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

链接: https://www.fly63.com/article/detial/11784


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK