Teleport 组件是 Vue.js 3 中引入的特性之一,它允许将组件的内容传送(teleport)到当前组件之外的目标位置,这在处理复杂的布局、模态框等方案时非常有用。
A.vue
<template><div class="dialog"><header class="header"><div>我是弹框</div><el-icon><CloseBold></CloseBold></el-icon></header><main class="main">我是内容</main><footer class="footer"><el-button size="small">取消</el-button><el-button size="small" type="priamary">确定</el-button></footer></div>
</template><script setup lang="ts"></script><style lang="less" scoped>
.dialog {width: 400px;height: 400px;background-color: #282c34;display: flex;flex-direction: column;position: absolute;left: 50%;top: 50%;margin-left: -200px;margin-top: -200px;
}.header {display: flex;color: aliceblue;border-bottom: 1px solid #636466;padding: 10px;justify-content: space-between;
}.main {flex: 1;color: #fff;padding: 10px;
}.footer {border-top: 1px solid gainsboro;padding: 10px;display: flex;justify-content: flex-end;}</style>
App.vue
<template><div class="parent"><h1>我是父级</h1><A></A></div>
</template><script setup lang="ts">
import { ref,reactive } from 'vue';
import A from './components/A.vue';</script><style scoped>
* {padding: 0;margin: 0;}
.parent {background: yellow;height: 50vh;position: relative;
}</style>
加入 Teleport 传送组件后,不再受父级影响
App.vue
<template><div class="parent"><h1>我是父级</h1><Teleport :disabled="false" to="body"><!-- disabled 控制 teleport 是否禁用,to 控制 teleport 的目标 --><A></A></Teleport></div>
</template><script setup lang="ts">
import { ref,reactive } from 'vue';
import A from './components/A.vue';</script><style scoped>
* {padding: 0;margin: 0;}
.parent {background: yellow;height: 50vh;position: relative;
}</style>