前言
弹窗用的比较多可以封装起来 当然封装方法很多,这只是其中一种
具体往下来看
效果图
代码
所封装的弹窗dialog.vue
<template>
<el-dialog
top="20vh"
class="el-dialog-cus"
v-bind="{...$attrs, ...{title, width, center}}"
:visible="visible"
:before-close="beClose"
append-to-body
>
<slot></slot>
<div slot="footer">
<el-button @click="cancel" plain>{{btnTxt[0]}}</el-button>
<el-button @click="confirm" type="primary" v-if="btnTxt[1]">{{btnTxt[1]}}</el-button>
</div>
</el-dialog>
</template>
<script>
export default {
inheritAttrs: false,
props: {
title: {
type: String,
default: "提示",
},
width: {
type: String,
default: "420px",
},
center: {
type: Boolean,
default: true,
},
autoClose: {
type: Boolean,
default: true,
},
beforeClose: {
type: Function,
default: () => {}
},
btnTxt: {
type: Array,
default: () => ["取消", "确定"],
},
},
data() {
return {
visible: false,
};
},
methods: {
open(ok) {
this.ok = ok;
this.visible = true;
},
cancel() {
this.visible = false;
},
confirm() {
let cancel = () => this.cancel();
this.ok(cancel);
this.autoClose && cancel();
},
beClose(done) {
done();
this.beforeClose();
this.cancel();
},
},
};
</script>
<style lang="scss">
.el-dialog-cus {
.el-dialog {
padding: 8px;
}
.el-dialog__title {
font-weight: bold;
}
.el-dialog__header {
padding: 20px 0 12px;
}
.el-dialog__headerbtn {
top: 8px;
right: 8px;
}
.el-dialog--center .el-dialog__body {
padding: 0 24px;
text-align: center;
}
.el-dialog__footer {
padding: 20px;
.el-button {
padding: 8px 20px;
& + .el-button {
margin-left: 40px;
}
}
}
}
</style>
页面使用
<template>
<div>
<el-button @click="open">点我打开</el-button>
<Dialog ref="dialog" :title="title" :width="width" :center="center" :btnTxt="btnTxt" :beforeClose="beforeClose"><span>this is a dialog</span></Dialog>
</div>
</template>
<script>
import Dialog from "@/components/dialog";
export default {
components: {
Dialog,
},
data() {
return {
width: '500px',
title: '温馨提示',
center: true,
btnTxt: ['取消', '提交'],
};
},
methods: {
open() {
this.$refs.dialog.open(cancel => {
console.log('点击提交按钮了')
});
},
beforeClose(){
console.log('关闭前');
},
}
};
</script>
细心的小伙伴会发现
当我点击弹窗外的区域弹窗也会自动关闭撒
怎么让其不关闭呢
请看下面
第一种:(单个设置)
在el-dialog标签中添加:close-on-click-modal="false"即可
<el-dialog title="标题" :close-on-click-modal="false" :visible.sync="dialogFormVisible">
弹窗内容
</el-dialog>
第二种:(全局设置)
在mian.js里面引入并设置:
import ElementUI from 'element-ui';
ElementUI.Dialog.props.closeOnClickModal.default = false
参考