Vue Teleport
Vue 的 <Teleport>
标签用于将内容移动到 DOM 结构中的不同位置。
<Teleport> 和 'to' 属性
要将某些内容移动到 DOM 结构中的其他位置,我们使用 Vue 的 <Teleport>
标签包裹内容,并使用 'to' 属性来定义移动到的位置。
<Teleport to="body">
<p>Hello!</p>
</Teleport>
'to' 属性的值以 CSS 符号表示法给出,因此,如果我们想将一些内容发送到 body 标签(如上面的代码所示),我们只需编写 <Teleport to="body">
。
加载页面后,我们可以通过检查页面来看到内容已被移至 body 标签。
示例
CompOne.vue
:
<template>
<div>
<h2>Component</h2>
<p>This is the inside of the component.</p>
<Teleport to="body">
<div id="redDiv">Hello!</div>
</Teleport>
</div>
</template>
运行示例 »
如果我们右键单击页面并选择“检查”,我们可以看到红色的 <div>
元素已被移出组件,并移到了 <body>
标签的末尾。

我们也可以例如有一个带有 id <div id="receivingDiv">
的标签,然后通过使用 <Teleport to="#receivingDiv">
包裹我们想要传送/移动的内容,将一些内容传送/移动到该 <div>
中。
被传送元素的脚本和样式
即使某些内容被 <Teleport>
标签移出了组件,<script>
和 <style>
标签中与被移动内容相关的代码仍然可以正常工作。
示例
尽管被传送的 <div>
元素在编译后不再位于组件内,但来自 <style>
和 <script>
标签的相关代码仍然适用于该 <div>
标签。
CompOne.vue
:
<template>
<div>
<h2>Component</h2>
<p>This is the inside of the component.</p>
<Teleport to="body">
<div
id="redDiv"
@click="toggleVal = !toggleVal"
:style="{ backgroundColor: bgColor }"
>
Hello!<br>
Click me!
</div>
</Teleport>
</div>
</template>
<script>
export default {
data() {
return {
toggleVal: true
}
},
computed: {
bgColor() {
if (this.toggleVal) {
return 'lightpink'
}
else {
return 'lightgreen'
}
}
}
}
</script>
<style scoped>
#redDiv {
margin: 10px;
padding: 10px;
display: inline-block;
}
#redDiv:hover {
cursor: pointer;
}
</style>
运行示例 »