# Teleport


Teleport 传送门组件提供一种简洁的方式可以指定它里面内容的父元素。

  • Props:

    • to - string 必填
    • disabled - boolean 可选
  • 示例:

<!-- ModalPopupComp.vue  无disabled -->
<template>
	<button @click="ModalOpen = true">弹出一个模态窗口</button>
	<!-- to 指定 teleport 内容放在哪里 -->
	<teleport to="body">
		<div v-if="ModalOpen" class="modal">
			<div class="modal-inner">
				<div>这是一个模态弹窗,我的父元素是body。</div>
				<button @click="ModalOpen = false">关闭</button>
			</div>
		</div>
	</teleport>
</template>
1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- ModalPopupComp.vue  有disabled -->
<template>
	<button @click="ModalOpen = true">弹出一个模态窗口</button>
	<!-- 加上 disabled,teleport 功能失效,插槽内容将不会被移动到任何位置,
            而是在引用了 teleport 的父组件中渲染。 -->
	<teleport to="body" disabled>
		<div v-if="ModalOpen" class="modal">
			<div class="modal-inner">
				<div>这是一个模态弹窗,我的父元素是body。</div>
				<button @click="ModalOpen = false">关闭</button>
			</div>
		</div>
	</teleport>
</template>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- ModalPopupComp.vue  公共部分 -->
<script>
	import { ref } from 'vue'
	export default {
		setup() {
			const ModalOpen = ref(false)
			return { ModalOpen }
		},
	}
</script>

<style scoped>
	.modal {
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: rgba(0, 0, 0, 0.5);
	}
	.modal-inner {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		padding: 20px;
		width: 500px;
		height: 300px;
		background-color: #fff;
		border-radius: 5px;
		box-sizing: border-box;
	}
</style>
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
<!-- Layout.vue -->
<template>
	<modal-popup-comp />
</template>

<script>
	import ModalPopupComp from './ModalPopupComp.vue'
	export default {
		components: {
			ModalPopupComp,
		},
	}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13