Vue3 Teleport

为什么需要 Teleport?

以 Dialog 组件为例,通常需要在一个组件中引入 Dialog 组件。然而,有时一部分逻辑属于 Dialog 所在的组件中,从技术角度来看,最好将这一部分移动到根节点之外的位置。

另外一个问题, 当 Dialog 组件使用 position: absolute  相对于它所在的组件进行绝对定位时,样式变得十分混乱。

使用 Teleport

lol-tp-7.png

teleport 意为传送,它提供了一种干净的方法,允许我们控制在 DOM 中哪个父节点下呈现 HTML。

Step1: 创建传送的目标节点,此处为 index.html 中的和根节点同级的 id 为 model 的节点。

...
<div id="app"></div>
<div id="model"></div>
...

Step2: 使用 <teleport> 将需要被传送的组件包裹起来,   此处将 Dialog 包裹。

<template>
  <teleport>
    <div>I'am a Dialog.</div>
  </teleport>
</template>

Step3:指定 telport 的 to  属性,告诉它要传送到 id 为 model 的节点。

<template>
  <teleport to="#modal">
    <div>I'am a Dialog.</div>
  </teleport>
</template>

接下来无论在哪个组件中使用该 Dialog 组件,都会将它渲染到 id 为 model 的节点下。这就实现了传送的功能。

Component.vue

<template>
  <div>
    <Dialog></Dialog>
  </div>
</template>

<script>
import Dialog from "./components/Dialog.vue";
export default {
  components: {
    Dialog
  },
}
</script>

image.png

值得注意的是,即使在不同的地方渲染 Dialog,它仍将是 Component.vue 的子级,并将从中接收 props。还可以将多个 teleport 挂在到同一个目标节点上,挂载的顺序是从前到后,即先挂载的位于前面。

posted @ 2020-11-26 10:56  guangzan  阅读(591)  评论(0编辑  收藏  举报