Teleport(传送门)是一个内置组件,它可以将一个组件内部的一部分模板“传送”到该组件的DOM结构外层的位置去。这个特性允许你突破组件的层级限制,将某些元素渲染到DOM树的其他位置,比如body标签或者其他任何DOM节点下。
<template>
<button @click="open = true">Open Modal</button>
<Teleport to="body">
<div v-if="open" class="modal">
<p>Hello from the modal!</p>
<button @click="open = false">Close</button>
</div>
</Teleport>
</template>
<script setup>
import { ref } from 'vue'
const open = ref(false)
</script>
<style scoped>
.modal {
position: fixed;
z-index: 999;
top: 20%;
left: 50%;
width: 300px;
margin-left: -150px;
}
</style>
-
没有Teleport的情况下,modal的层级并没有突破组件
-
在Teleport的情况下,modal的层级有突破组件