Vue <Teleport> 组件

实例

使用内置的 <Teleport> 组件将 <div> 元素移动到 <body>

  1. <Teleport to="body">
  2. <div id="redDiv">Hello!</div>
  3. </Teleport>

定义与用法

内置的 <Teleport> 组件与 to 一起使用,以将一个元素从当前 HTML 结构中移出,并移动到 DOM 中已安装的另一个元素中。

要查看元素是否已通过 <Teleport> 组件实际移动到某个位置,您可能需要右键单击并检查页面。传送的元素将在目的地中已经安装的其他元素之后结束。因此,如果不止一个元素被传送到同一个目的地,最后一个被传送的元素将最终低于其他被传送元素。

如果 <Teleport> 用于移动组件,则与该组件之间通过 provide/inject(提供/注入)或 prop/emit 的通信仍然像以前一样工作,就好像该组件没有移动一样。

此外,如果某些内容从带有 <Teleport> 的组件中移出,Vue 会确保 <script><style> 标记中组件内的相关代码仍然适用于移动的内容。请参阅下面的实例。


Props

Prop描述试一试
to必填。字符串。指定目标的名称试一试
disabled可选。布尔值。指定是否应禁用传送功能试一试

更多实例

实例

<style><script> 标记中的相关代码仍然适用于传送的 <div> 标记,即使编译后它不再在组件中。

CompOne.vue:

  1. <template>
  2. <div>
  3. <h2>Component</h2>
  4. <p>This is the inside of the component.</p>
  5. <Teleport to="body">
  6. <div
  7. id="redDiv"
  8. @click="toggleVal = !toggleVal"
  9. :style="{ backgroundColor: bgColor }"
  10. >
  11. Hello!<br>
  12. Click me!
  13. </div>
  14. </Teleport>
  15. </div>
  16. </template>
  17. <script>
  18. export default {
  19. data() {
  20. return {
  21. toggleVal: true
  22. }
  23. },
  24. computed: {
  25. bgColor() {
  26. if (this.toggleVal) {
  27. return 'lightpink'
  28. }
  29. else {
  30. return 'lightgreen'
  31. }
  32. }
  33. }
  34. }
  35. </script>
  36. <style scoped>
  37. #redDiv {
  38. margin: 10px;
  39. padding: 10px;
  40. display: inline-block;
  41. }
  42. #redDiv:hover {
  43. cursor: pointer;
  44. }
  45. </style>
实例

disabled 禁用布尔值的 prop 通过一个按钮进行切换,这样 <div> 元素要么被传送,要么不被传送。

CompOne.vue:

  1. <template>
  2. <div>
  3. <h2>Component</h2>
  4. <p>This is the inside of the component.</p>
  5. <button @click="teleportOn = !teleportOn">Teleport on/off</button>
  6. <Teleport to="body" :disabled="teleportOn">
  7. <div id="redDiv">Hello!</div>
  8. </Teleport>
  9. </div>
  10. </template>
  11. <script>
  12. export default {
  13. data() {
  14. return {
  15. teleportOn: true
  16. }
  17. }
  18. }
  19. </script>
  20. <style scoped>
  21. #redDiv {
  22. background-color: lightcoral;
  23. margin: 10px;
  24. padding: 10px;
  25. width: 100px;
  26. }
  27. </style>

分类导航