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 标记。
我们可以看到,通过在页面加载后检查页面,内容被移动到了 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>
如果我们右键单击页面并选择 'Inspect',我们可以看到红色的 <div> 元素被移出组件并移到 <body> 标记的末尾。
例如,我们还可以有一个 id 为 <div id="receivingDiv"> 的标签,并通过在我们想要传送/移动的内容周围使用 <Teleport to="#receivingDiv"> 将一些内容传送到 <div>。
Teleport 元素的脚本和风格
即使某些内容被移出带有 <Teleport> 标记的组件,<script> 和 <style> 标记中组件内部的相关代码仍然适用于移动的内容。
实例
<style> 和 <script> 标记中的相关代码仍然适用于传送的 <div> 标记,即使编译后它不再在组件中。
CompOne.vue
<template><div><h2>Component</h2><p>This is the inside of the component.</p><Teleport to="body"><divid="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>