Teleport
<Teleport>
只改变了渲染的 DOM 结构,它不会影响组件间的逻辑关系。
<teleport>
的组件保持逻辑上的父子关系。传入的 props 和触发的事件也会照常工作。
App.vue
<template>
<div class="App">
<!--
将组件传送到body元素下
-->
<Teleport to="body">
<Mask ref="maskRef" :appNum="10" @maskNum="maskNum"></Mask>
</Teleport>
<button @click="showMask">显示模态框</button>
</div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import Mask from './components/Mask.vue';
const maskRef = ref()
function showMask() {
maskRef.value.isShow = true
}
function maskNum(num) {
console.log(num);
}
</script>
<style scoped></style>
Mask.vue
<template>
<div class="mask" v-show="isShow">
<h1>模态框{{ appNum }}</h1>
<button @click="isShow = false">close</button>
</div>
</template>
<script setup>
import { ref, reactive } from 'vue'
defineProps({
appNum: {
type: Number,
Object: 0
}
})
const emit = defineEmits(['maskNum'])
emit('maskNum', 9)
let isShow = ref(false)
defineExpose({
isShow
})
</script>
<style scoped>
.mask {
position: fixed;
left: 0;
right: 0;
top: 0;
z-index: 9;
height: 100vh;
text-align: center;
background-color: rgba(204, 204, 204, .5);
}
</style>
Mask传送到body元素下,组件间的逻辑关系不变