vue3中的teleport
文章类型:Vue
发布者:hp
发布时间:2025-02-13
在vue3中,出现了一个新的特性Teleport ,是什么呢?
1:提供一种便捷的方式将组件中插槽内容渲染到DOM中的另外一个位置,不受组件层的限制
2:通过Telport,将组件的内容“传送”到DOM树其他位置,更好的提高了代码的可读性和维护性
3:帮助控制组件的渲染位置和样式
1:用法
<template>
<Teleport to="目标选择器">
<内嵌组件/>
</Teleport>
</template>
<Teleport to="body">
<div class="modal">
<div class="modal-content">
<slot></slot>
<button @click="closeModal">关闭</button>
</div>
</div>
</Teleport>
2:说明
to属性就是你希望组件内容渲染到的目标为止
1:模态框
2:通知和提示
3:下拉菜单和工具提示
4:上下文菜单
1:Teleport将组件插槽内容渲染到DOM 其他指定位置
2:在很多特定场景更加方便快捷
3:减少DOM操作和提高代码复用性