為什么需要 Teleport?
以 Dialog 組件為例,通常需要在一個組件中引入 Dialog 組件。然而,有時一部分邏輯屬於 Dialog 所在的組件中,從技術角度來看,最好將這一部分移動到根節點之外的位置。
另外一個問題, 當 Dialog 組件使用 position: absolute
相對於它所在的組件進行絕對定位時,樣式變得十分混亂。
使用 Teleport
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>
值得注意的是,即使在不同的地方渲染 Dialog,它仍將是 Component.vue 的子級,並將從中接收 props。還可以將多個 teleport 掛在到同一個目標節點上,掛載的順序是從前到后,即先掛載的位於前面。