父组件
<template>
<div class="outer">
<h3>Teleport</h3>
<div>
<MyModal />
</div>
</div>
</template>
<script setup>
import { ref, reactive, defineAsyncComponent } from 'vue'
import MyModal from './components/MyModal.vue'
</script>
<style scoped>
.outer {
background: blueviolet;
height: 600px;
position: relative;
}
</style>
子组件
<template>
<button @click="open = true">显示modal</button>
<Teleport to="body">
<div v-if="open" class="modal">
<p>Hello modal!</p>
<button @click="open = false">隐藏modal</button>
</div>
</Teleport>
</template>
<script setup>
import { ref } from 'vue'
const open = ref(false)
</script>
<style scoped>
.modal {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
position: absolute;
width: 300px;
height: 200px;
background: pink;
z-index: 999;
top: 50%;
left: 50%;
margin-left: -150px;
margin-top: -100px;
}
</style>
虽然.outer上有相对定位,但是modal弹窗还是会根据body定位