Teleport可以把组件的某一部分 DOM 渲染到 Vue 组件树之外的任意指定位置,而逻辑(状态、事件)仍保留在原组件内部。

这个特性非常适用于模态框、弹出框等需要在页面特定位置显示的组件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

<div id="Application">
<div style="position: absolute; width: 50px;">
<my-alert></my-alert>
</div>
</div>
<script>
const App = Vue.createApp({})
App.component("my-alert", {
template: `
<div>
<button @click="show = true">弹出弹窗</button>
</div>
<teleport to="body">
<div v-if="show" style="
text-align: center;
padding: 20px;
position: absolute;
top: 30%;
left: 30%;
width: 40%;
border: black solid 2px;
background-color: white;
">
<h3>弹窗</h3>
<button @click="show = false">隐藏弹窗</button>
</div>
</teleport>
`,
data() {
return {
show: false
};
}
});
App.mount('#Application')
</script>

如上所示

  • 弹窗覆盖全屏,不受父级 position: absolute; width: 50px; 的限制;
  • show 状态仍由 <my-alert> 组件自身管理,不需要额外的全局状态或事件总线;