最近几个页面都用到一些通用的弹窗,为了减少重复开发,于是想做成一个通用的组件,再加上这个过程中涉及到父子之间的传参,所以这次组件封装具有参考意思,故记录该篇文章用于以后的使用参考。
需求:封装一个通用的弹窗组件(非重点:弹窗中包含下拉选择框以及特定标签触发的输入框),父类传参到通用组件控制弹窗的展示与关闭,子类将用户选取的参数传递到父类。
通用弹窗子组件:CubeFunTypeDialog.vue
<template>
<el-dialog
title="自定义"
:close-on-click-modal="false"
:close-on-press-escape="false"
:show-close="false"
:visible.sync="funTypeVisible"
>
<div style="text-align: left">
<div>
<span>度量函数:</span>
<el-select v-model="columnFunc" placeholder="请选择">
<el-option
v-for="item in columnFuncs"
:key="item.value"
:label="item.label"
:value="item.value"
>
</el-option>
</el-select>
</div>
<br />
<div>
<span>返回类型:</span>
<el-select v-model="columnType" placeholder="请选择">
<el-option
v-for="item in columnTypes"
:key="item.value"
:label="item.label"
:value="item.value"
>
</el-option>
</el-select>
<span style="margin-left: 5px"
><el-input
v-model="customizeType"
v-if="columnType == 'customize'"
placeholder="请输入内容"
style="width: 20%"
></el-input
></span>
</div>
</div>
<el-button @click="confirmFunType">确定</el-button>
</el-dialog>
</template>
<script>
export default {
//接收父传子的参数,如果用{}表示props,还可以定义参数的类型
props: ["funTypeVisible"],
data() {
return {
columnFunc: "",
columnFuncs: [
{
label: "COUNT",
value: "COUNT",
},
{
label: "SUM",
value: "SUM",
},
{
label: "MAX",
value: "MAX",
},
{
label: "MIN",
value: "MIN",
},
{
label: "COUNT_DISTINCT",
value: "COUNT_DISTINCT",
},
],
customizeType: "",
columnType: "",
columnTypes: [
{
label: "STRING",
value: "STRING",
},
{
label: "BIGINT",
value: "BIGINT",
},
{
label: "DOUBLE",
value: "DOUBLE",
},
{
label: "FLOAT",
value: "FLOAT",
},
{
label: "INT",
value: "INT",
},
{
label: "BOOLEAN",
value: "BOOLEAN",
},
{
label: "自定义",
value: "customize",
},
],
};
},
methods: {
confirmFunType() {
if (this.columnFunc == "") {
this.$message("度量函数不能为空!");
} else {
var param = {
columnFunc: this.columnFunc,
columnType: this.columnType,
customizeType: this.customizeType,
};
this.$emit('sendFunAndType', param);
this.columnFunc = "";
this.columnType = "";
this.customizeType = "";
}
},
},
};
</script>
<style>
</style>
其中 props: ["funTypeVisible"] 用于通用子组件接收父传子的参数,如果用{}表示props,还可以定义参数的类型,如下:
props: {
funTypeVisible:Boolean
}
另外 confirmFunType方法中 this.$emit('sendFunAndType', param) 用于子组件提交参数到父组件,只要父组件监听该事件即可。另外再提一句,在 this.$emit方法后还有三句重新赋值的语句,这个是为了让下一次的弹窗选型回归到初始值。
父组件调用:
<CubeFunTypeDialog :funTypeVisible=funTypeVisible v-on:sendFunAndType="listenFunAndType"></CubeFunTypeDialog>
listenFunAndType(param){
console.log(param.columnFunc)
console.log(param.customizeType)
console.log(param.columnType)
//关闭弹窗
this.funTypeVisible = false;
},
注意:父组件中省略了在data中对funTypeVisible属性的定义,这个别忘记了。还有就是funTypeVisible默认值是false,记得要在需要弹窗的时候设置为true