其他分享
首页 > 其他分享> > vue3.0 的Teleport

vue3.0 的Teleport

作者:互联网

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

如图所示:
在这里插入图片描述
文件目录:
在这里插入图片描述

Child.vue代码:

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

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

<style>
.child{
    background-color: gray;
    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: rosybrown;
}
</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>
  <h3>我是App组件</h3>
  <Child/>
</template>

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

<style>
.app{
  background-color: rgb(221, 69, 216);
  padding: 10px;
}

</style>

效果:
在这里插入图片描述

标签:Teleport,vue,background,color,Son,vue3.0,Dialog,Child
来源: https://blog.csdn.net/qq_46582421/article/details/122509333