描述

teleport组件提供了一种干净的方法,让组件的html在父组件界面外的特定标签(很可能是body)下插入显示。说白了就是在这个组件里的元素不会嵌套在id = 'app的容器里显示,而是挂载在body标签上。


示例

1、父组件

Html

<template>
	<h2>App</h2>
	<modal-button></modal-button>
</template>

TypeScript

import ModalButton from './ModalButton.vue'

export default {
	components: {
		ModalButton
	}
	setup() {
		return {}
	},
}

2、子组件

Html

<template>
	<button @click="modalOpen = true">
		Open full screen modal! (With teleport!)
	</button>

	<teleport to="body">
		<div v-if="modalOpen" class="modal">
			<div>
				<button @click="modalOpen = false">Close</button>
			</div>
		</div>
	</teleport>
</template>

TypeScript

import { ref } from 'vue'

export default {
	name: 'modal-button',
	setup () {
		const modalOpen = ref(false);
		
		return {
			modalOpen
		}
	}
}

Style

.modal {
	position: absolute;
	top: 0; right: 0; bottom: 0; left: 0;
	background-color: rgba(0,0,0,.5);
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.modal div {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background-color: white;
	width: 300px;
	height: 300px;
	padding: 5px;
}
Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐