vue弹出框的封装和点击弹出框外部的事件触发
封装主要利用vue之间的组件通信
Home.vue 父组件
<template>
<div>
<div class="box_popup">
<div class="popup_title">弹出框</div>
<button @click="tan">点击弹出弹出层</button>
<!--
title:标题内容 默认值:默认标题
content_text:自定义文字内容 默认值:默认内容
template:插槽内容,可插入文本框,HTML,图片...
hidden:判断弹出层显示隐藏
popup_sub:子组件确定事件
popup_clo:子组件的取消事件
clo_box:点击了弹出框外部内容
-->
<Popup
title="父组件标题"
:hidden="this.ishidden"
@popup_sub="popup_submit"
@popup_clo="popup_close"
@clo_box="close_box"
>
</Popup>
</div>
</div>
</template>
<script>
import Popup from "../components/Popup";
export default {
components: {
Popup,
},
data() {
return {
ishidden: false,
};
},
methods: {
//点击弹出弹出层
tan() {
this.ishidden = true;
},
//子组件的确定事件
popup_submit() {
this.ishidden = false;
console.log("点击了确定按钮");
},
//子组件的取消事件
popup_close() {
this.ishidden = false;
console.log("点击了取消事件");
},
//点击弹出框以外触发
close_box() {
this.ishidden = false;
console.log("点击了弹出框外部");
},
},
};
</script>
<style scoped>
.box_popup {
border: 1px solid red;
}
.popup_title {
text-align: center;
font-size: 30px;
}
</style>
Popup.vue 子组件
<template>
<div class="box" v-show="this.hidden" @click.stop="clo_box">
<div class="popup_content">
<div class="popup_title">{{ this.title }}</div>
<div class="popup_center">
<div v-if="this.content_text">{{ this.content_text }}</div>
<slot></slot>
</div>
<div class="popup_bottom">
<button @click="popup_sub">确定</button>
<button @click="popup_clo">取消</button>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
title: {
type: String,
default: "默认标题",
},
content_text: {
type: String,
default: "",
},
hidden: {
type: Boolean,
default: false,
},
},
methods: {
//点击确定事件
popup_sub() {
this.$emit("popup_sub");
},
//点击了取消事件
popup_clo() {
this.$emit("popup_clo");
},
//点击了弹出框以外区域
clo_box(e) {
if (e.target._prevClass == "box") {
this.$emit("clo_box")
}
},
},
};
</script>
<style scoped>
.box {
background-color: rgba(128, 128, 128, 0.507);
width: 100%;
height: 100%;
position: absolute;
top: 0px;
}
.popup_content {
background-color: white;
padding: 1%;
border-radius: 20px;
width: 40%;
margin: 10% auto;
}
.popup_title {
text-align: center;
font-weight: 600;
font-size: 30px;
}
.popup_center {
padding: 10%;
font-size: 20px;
}
.popup_bottom {
display: flex;
justify-content: space-around;
}
button {
width: 25%;
height: 20%;
padding: 2%;
border: 1px solid gray;
border-radius: 10px;
}
button:nth-child(1) {
background-color: orangered;
color: white;
font-size: 20px;
}
button:nth-child(2) {
background-color: gray;
color: black;
font-size: 20px;
}
</style>