在一些場景中,比如使用modal時,我們想要將modal放在具體的vue頁面中,功能與位置保持一致。但是在展示時,又希望直接將它放在body下,方便實現(xiàn)定位樣式。面對功能位置與樣式位置的不統(tǒng)一,vue3中提供一對<teleport ></teleport>標簽用于移動dom的位置到指定元素。
modal組件:
<template>
<div class='modal'>
<p>這是一個模態(tài)框</p>
<button>關(guān)閉</button>
</div>
</template>
<script>
export default {
name: 'modal',
};
</script>
<style lang='scss' scoped>
.modal{
position: absolute;
left: 40%;
top: 40%;
width: 100px;
height: 100px;
border: 1px skyblue solid;
}
</style>
父組件:
<template>
<div class='test'>
<p>這是父頁面</p>
<modal/>
</div>
</template>
<script>
import modal from './modal';
import { defineComponent, ref} from 'vue';
export default defineComponent({
name: 'test',
components: {
modal
},
});
</script>
<style lang='scss' scoped>
.test {
position: absolute;
left: 100px;
top: 100px;
width: 200px;
border: 1px solid #000;
color: #00EAFF;
}
</style>
此時dom結(jié)構(gòu)為:

image.png
如果我們嵌套teleport標簽,標簽上的to參數(shù)表示要將包裹的內(nèi)容所移動到的父級元素。父組件變?yōu)椋?/p>
<template>
<div class='test'>
<p>這是父頁面</p>
<teleport to='body'>
<modal/>
</teleport>
</div>
</template>
dom結(jié)構(gòu)變?yōu)椋?/p>

image.png