vue3知识点:Teleport组件

在这里插入图片描述

五、新的组件

2.Teleport

问题:什么是Teleport?

答案:Teleport 是一种能够将我们的组件html结构移动到指定位置的技术。

<teleport to="移动位置">
	<div v-if="isShow" class="mask">
		<div class="dialog">
			<h3>我是一个弹窗</h3>
			<button @click="isShow = false">关闭弹窗</button>
		</div>
	</div>
</teleport>

注意点1:

问题:使用传送的好处?

答案:不影响其他组件html的结构,举例说明我son组件有个div,我有个显示按钮,有个隐藏按钮,如果不使用Teleport,那么每次展示div时候会影响别的组件html结构,而使用Teleport就不会影响,具体效果看案例结果一目了然。

注意点2:
好处是方便定位,直接把html结构直接传送走,比如案例的传送至body处或者其他处。

案例

完整代码

项目结构

在这里插入图片描述

main.js

//引入的不再是Vue构造函数了,引入的是一个名为createApp的工厂函数
import { createApp } from 'vue'
import App from './App.vue'

//创建应用实例对象——app(类似于之前Vue2中的vm,但app比vm更“轻”)
const app = createApp(App)

//挂载
app.mount('#app')

App.vue

<template>
	<div class="app">
		<h3>我是App组件</h3>
		<Child/>
	</div>
</template>

<script>
	import Child from './components/Child'
	export default {
		name:'App',
		components:{Child},
	}
</script>

<style>
	.app{
		background-color: gray;
		padding: 10px;
	}
</style>

Child.vue

<template>
	<div class="child">
		<h3>我是Child组件</h3>
		<Son/>
	</div>
</template>

<script>
	import Son from './Son'
	export default {
		name:'Child',
		components:{Son},
	}
</script>

<style>
	.child{
		background-color: skyblue;
		padding: 10px;
	}
</style>

Son.vue

<template>
	<div class="son">
		<h3>我是Son组件</h3>
		<Dialog/>
	</div>
</template>

<script>
	import Dialog from './Dialog.vue'
	export default {
		name:'Son',
		components:{Dialog}
	}
</script>

<style>
	.son{
		background-color: orange;
		padding: 10px;
	}
</style>

Dialog.vue

<template>
	<div>
		<button @click="isShow = true">点我弹个窗</button>
		<teleport to="body">
			<div v-if="isShow" class="mask">
				<div class="dialog">
					<h3>我是一个弹窗</h3>
					<h4>一些内容</h4>
					<h4>一些内容</h4>
					<h4>一些内容</h4>
					<button @click="isShow = false">关闭弹窗</button>
				</div>
			</div>
		</teleport>
	</div>
</template>

<script>
	import {ref} from 'vue'
	export default {
		name:'Dialog',
		setup(){
			let isShow = ref(false)
			return {isShow}
		}
	}
</script>

<style>
	.mask{
		position: absolute;
		top: 0;bottom: 0;left: 0;right: 0;
		background-color: rgba(0, 0, 0, 0.5);
	}
	.dialog{
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%,-50%);
		text-align: center;
		width: 300px;
		height: 300px;
		background-color: green;
	}
</style>

结果展示:

在这里插入图片描述

使用Teleport-案例结果.gif

在这里插入图片描述

未使用Teleport-案例结果.gif

本人其他相关文章链接

1.《vue3第五章》新的组件,包含:Fragment、Teleport、Suspense
2.vue3知识点:Teleport组件
3.vue3知识点:Suspense组件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘大猫.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值