在 Vue 3 中,<Teleport>
是一个强大的功能,它允许你将一个组件的模板内容渲染到 DOM 中的不同位置,而不是在该组件的父级组件的 DOM 层级中渲染。
以下是一个基本的使用示例:
// src/dialog.vue 公共弹窗
<template>
<div class="portals">
<button @click="ShowNotification">trigger Notification</button>
<teleport to='#portal'>
<div v-if="isOpen" class="notification">
this is rendering outside of this child component
</div>
</teleport>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup () {
const isOpen = ref(false);
var closePopup;
const ShowNotification = () => {
isOpen.value = true
clearTimeout(closePopup);
closePopup = setTimeout(() => {
isOpen.value = false
}, 2000)
};
return {
isOpen,
ShowNotification
}
}
}
</script>
// index.html
<!-- portal -->
<div id="portal"></div>
// main.js
const dialog = createApp(Dialog)
dialog.mount('#portal')
在这个例子中,<Teleport>
组件将内部的<div>
内容渲染到了body
元素中。
你还可以通过传递一个 CSS 选择器字符串或一个实际的 DOM 元素引用,将内容传送到特定的目标位置。
<template>
<div>
<Teleport to="#my-target-element">
<div>这部分内容将被渲染到具有 id 为 my-target-element 的元素内。</div>
</Teleport>
</div>
</template>
或者使用一个动态的目标:
<template>
<div>
<input type="text" v-model="targetId">
<Teleport :to="targetId? `#${targetId}` : undefined">
<div>这部分内容将根据输入的目标 ID 进行渲染。</div>
</Teleport>
</div>
</template>
<script setup>
import { ref } from 'vue';
const targetId = ref('');
</script>
<Teleport>
在处理模态框、弹出窗口或需要将特定内容放置在特定位置而不受父组件布局限制的情况下非常有用。
需要注意的是,被<Teleport>
传送的内容会脱离其原始组件的作用域,这意味着父组件中的样式和事件绑定可能不会自动应用到传送的内容上。如果需要,可以在传送的目标位置手动添加适当的样式和事件处理。