使用vue封装一个弹出框
在我了解的vue中,一般封装主要就是用的就是组件通信,即父传子,子传父,兄弟传值。如果这点不懂,去看看我的博客:vue组件通信
下面就说说,怎么使用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>
接下来就是子组件的代码(这个就是一个简单的弹出框的封装,在写小的案例的时候可以用到,如果是大的项目那就需要自己来改点内容了)
<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>
细讲:
-
1、在父组件中引入子组件(Popup.vue),子组件就是封装的弹出层,刚开始不需要实现功能,主要就是页面的一个布局,在这里我就不多说了,毕竟。。。。
-
2、在子组件中定义props,在props里定义需要由父组件传过来的值,设置默认值和type类型;
-
3、主要就是在父组件中,通过动态绑定,把你要传的参数传给子组件;
-
4 、在子组件中,有两个事件就是点击取消和确认的事件,因为子组件不能直接修改父组件,因此呢是通过this.$emit来修改父组件的值;