Vue <Teleport> 组件
实例
使用内置的 <Teleport> 组件将 <div> 元素移动到 <body>:
<Teleport to="body"><div id="redDiv">Hello!</div></Teleport>
定义与用法
内置的 <Teleport> 组件与 to 一起使用,以将一个元素从当前 HTML 结构中移出,并移动到 DOM 中已安装的另一个元素中。
要查看元素是否已通过 <Teleport> 组件实际移动到某个位置,您可能需要右键单击并检查页面。传送的元素将在目的地中已经安装的其他元素之后结束。因此,如果不止一个元素被传送到同一个目的地,最后一个被传送的元素将最终低于其他被传送元素。
如果 <Teleport> 用于移动组件,则与该组件之间通过 provide/inject(提供/注入)或 prop/emit 的通信仍然像以前一样工作,就好像该组件没有移动一样。
此外,如果某些内容从带有 <Teleport> 的组件中移出,Vue 会确保 <script> 和 <style> 标记中组件内的相关代码仍然适用于移动的内容。请参阅下面的实例。
Props
| Prop | 描述 | 试一试 |
|---|---|---|
| to | 必填。字符串。指定目标的名称 | 试一试 |
| disabled | 可选。布尔值。指定是否应禁用传送功能 | 试一试 |
更多实例
实例
<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>
实例
disabled 禁用布尔值的 prop 通过一个按钮进行切换,这样 <div> 元素要么被传送,要么不被传送。
CompOne.vue:
<template><div><h2>Component</h2><p>This is the inside of the component.</p><button @click="teleportOn = !teleportOn">Teleport on/off</button><Teleport to="body" :disabled="teleportOn"><div id="redDiv">Hello!</div></Teleport></div></template><script>export default {data() {return {teleportOn: true}}}</script><style scoped>#redDiv {background-color: lightcoral;margin: 10px;padding: 10px;width: 100px;}</style>