视频

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>
    
    
    
    

components

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>

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>

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>

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>

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')

posted on 2023-04-23 22:28  垂序葎草  阅读(26)  评论(0编辑  收藏  举报