零基础学习Vue: 第28课 Vue子组件实现弹窗广告效果小案例:

零基础学习Vue: 第28课 Vue实现弹窗广告效果小案例:

原理:

通过子组件的$emit向父组件发射事件触发父主件内的函数方法使得父主件属性动态改变,再通过v-if实现显示 隐藏 / 弹窗 效果!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 引入vue -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <!-- 简单设置以下css样式 -->
    <style>
        *{margin:0;padding:0;}
        .mask{
            position:fixed;
            width:100%;
            height:100%;
            left:0;
            top:0;
            background-color:rgba(0,0,0,.35);
        }
        .mask .show{
            position: absolute;
            left:0;
            right:0;
            top:0;
            bottom: 0;
            width:600px;
            height:350px;
            margin:auto;
            background: #fff;
        }
        .mask .show button{
            position: absolute;
            right:0;
        }
    </style>
</head>
<body>

<div id="app" >
    <!-- 4.点击触父组件fn方法 将isShow值改成true 广告弹窗显示 -->
    <button @click="fn">点击弹窗</button>
    <!-- 5.引入子组件hide  v-if="isShow":当isShow=true显示  -->
    <!-- @xxx="close":接收组件件发射的xxx并触发父组件的close方法 isShow=fasle 窗口不显示 -->
    <hide v-if="isShow" @xxx="close"></hide>
</div>

<!-- 3.设置子组件标签样式 -->
<template id="hide">
    <div class="mask">
        <div class="show">
            假装这里面是广告
            <!-- button点击触发子组件的fn方法 -->
            <button @click="fn">关闭弹窗</button>
        </div>
    </div>
</template>

<script>

    //1.定义子组件hide 用于弹窗样式
    let hide = {
        template:'#hide',
        methods:{   //定义方法
            fn(){   //向父组件发射xxx事件
                this.$emit('xxx')
            }
        }
    }
    let vm = new Vue({
        el:'#app',
        data:{
            isShow:false,  //控制弹窗显示 true:显示
        },
        components:{    //2.注册主件
            hide
        },
        methods:{   //设置方法
            fn(){
                this.isShow = true;
            },
            close(){
                this.isShow = false;
            }
        }
    })
</script>
</body>
</html>

运行结果如下:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41614928/article/details/89489441
今日推荐