使用VUE3+teleport组件实现遮罩层和弹窗效果

先来看一下效果图;

 红色窗口就是弹窗,在弹窗后面添加了一层遮罩层,使用半透明的背景,使后面 孙组件 的按钮不能点。在点击 点我展示弹窗 这个按钮之前,是这样的效果

原理:

  • 实现之前需要使用VUE3写出连续的三个嵌套组件,也就是图示的 父组件、子组件和孙组件
  • 在孙组件中设置弹窗内容,可以引入其他组件,我这里为了方便就直接写在孙组件里面了
  • 如果仅仅是这样,弹窗内容只会显示在孙组件内部,很难将他定位在屏幕中央
  • 因此使用teleport组件,这个组件时VUE3独有的,他的作用是将组件html内容从一个地方传送到另外一个地方。我们可以借此弹窗的html内容传到body里面(关于teleport组件的用法,代码大家一看便知)
  • 设置遮罩层,这里有两个技巧:1、使用绝对定位保证遮罩层覆盖整个body;2、使用半透明的颜色覆盖遮罩层形成效果(rgba(0,0,0,0.5))

请看代码

组件结构图

文件结构图:vue3工程由vue-cli生成

扫描二维码关注公众号,回复: 14797033 查看本文章

关于组件的引用:

这里以APP组件引用父组件为例 

 以上图片也是app.vue的代码

Father_Demo.vue文件代码:(父组件)

<template>
    <div class="Father_container">
        <h1>我是父组件</h1>
        <Son_Demo></Son_Demo>
    </div>
</template>

<script>
    import Son_Demo from "./Son_Demo.vue";
    export default{
        components:{Son_Demo}
    }

</script>

<style scoped>
    .Father_container{
        width: 800px;
        height: 600px;
        padding: 20px;
        background-color: pink;
    }
</style>

Son_Demo.vue文件代码:(子组件)

<template>
    <div class="Son_container">
        <h1>我是子组件</h1>
        <Child_Demo></Child_Demo>
    </div>
</template>

<script>
    import Child_Demo from "./Child_Demo.vue";
    export default{
        components:{Child_Demo}
    }

</script>

<style scoped>
    .Son_container{
        width: 600px;
        height: 400px;
        padding: 20px;
        background-color: green;
    }   
</style>

Child_Demo.vue文件代码:(孙组件)

<template>
    <div class="Father_container">
        <h1>我是孙组件</h1>
        <button @click="flag = 1">点我展示弹窗</button>
        <teleport to="body">
            <div v-if="flag === 1" class="mask">  <!-- 设置遮罩层 -->
                <div class="chuang">
                    <h3>我是弹窗</h3>   
                    <h4>一些内容</h4>
                    <h4>一些内容</h4>
                    <h4>一些内容</h4>
                    <button @click="flag = 0">关闭弹窗</button>
                </div>
            </div>
        </teleport>
    </div>
</template>


<script>
    import {ref} from 'vue'
    export default{
        setup(){
            let flag = ref(0)


            return {
                flag
            }
        }
    }
</script>
<style scoped>
    .Father_container{
        width: 500px;
        height: 200px;
        padding: 20px;
        background-color: yellow;
    }
    .mask{   /* 遮罩层的写法 */
        position: absolute;
        top: 0;  bottom: 0; left: 0; right: 0;
        background-color: rgba(0, 0, 0, 0.5);
    }
    .chuang{
        width: 400px;
        height: 300px;
        text-align: center;
        border: 1px solid transparent;
        border-radius: 12px;
        background-color: red;
        margin: 15% auto; 
    }
</style>

有什么不懂的可以评论或私信我,需要源文件的uu也请私信我、

希望和诸君共勉!

猜你喜欢

转载自blog.csdn.net/qq_61567032/article/details/125757745