多的不说,先直接上代码
创建一个index文件,首先把你需要用到的组件封装起来
<template>
<el-dialog
:title="title"
:close-on-press-escape="false"
:close-on-click-modal="false"
:show-close="false"
:visible.sync="dialogVisible"
width="442px"
:before-close="handleClose"
append-to-body
>
<!-- 标题头插槽 -->
<div class="header-title" slot="title">
<i style="font-size: 20px" :class="'el-icon-' + type"></i>
<span class="title-style">{{ title }}</span>
</div>
<span>{{ message }}</span>
<span slot="footer" class="dialog-footer">
<el-button @click="handleClose">{{ cancelButtonText }}</el-button>
<el-button type="primary" @click="handleSubmit">{{ confirmButtonText }}</el-button>
</span>
</el-dialog>
</template>
<script>
export default {
props: {
title: {
type: String,
default: '提示',
},
message: {
type: String,
default: '是否确认该操作',
},
type: {
type: String,
default: 'warning',
},
cancelButtonText:{
type: String,
default:'取消'
},
confirmButtonText:{
type: String,
default:'确定'
}
},
data() {
return {
dialogVisible: true,
};
},
watch: {},
methods: {
handleClose() {
this.dialogVisible = false;
this.$emit('close');
},
handleSubmit(){
this.dialogVisible = false;
this.$emit('confirm')
},
},
};
</script>
<style lang="scss" scoped="scoped">
.el-dialog__wrapper {
::v-deep .el-dialog {
border-radius: 6px !important;
// margin-top: 15vh !important;
}
}
::v-deep .el-dialog__header {
padding: 28px 20px 10px 28px;
}
::v-deep .el-dialog__body {
padding: 9px 30px 13px 51px;
}
::v-deep .el-dialog__footer {
padding: 10px 30px 23px 20px;
}
.header-title {
display: flex;
align-items: center;
.title-style {
font-size: 14px;
margin-left: 3px;
font-weight: 600;
}
.el-icon-warning {
color: #e6a23c;
}
.el-icon-success {
color: #00c249;
}
.el-icon-info {
color: #909399;
}
.el-icon-error {
color: #fd4c23;
}
}
</style>
然后再创建一个js文件,文件命名因人而异,此处我的文件名叫useFun.js
import Vue from 'vue';
import messageBox from './index.vue'
export const useMessageBox = (message = '是否确认该操作', title = '提示', content = { type: 'warning',confirmButtonText:'确定',cancelButtonText:'取消' }) => {
return new Promise((resolve, reject) => {
//创建新的组件构造器
const Ctor = Vue.extend(messageBox);
//创建新的组件容器
const { type,confirmButtonText,cancelButtonText } = content;
const comp = new Ctor({
propsData: {
message,
title,
type,
confirmButtonText,
cancelButtonText
}
});
//挂载
comp.$mount();
document.body.appendChild(comp.$el);
//确认监听
comp.$once("confirm", ()=>{
resolve()
destroy()
})
//取消监听
comp.$once("cancel", ()=>{
reject()
destroy()
})
//销毁
function destroy() {
let timer = setTimeout(() => {
document.body.removeChild(comp.$el);
comp.$destroy();
clearTimeout(timer);
timer = null;
}, 300);
}
})
}
然后将当前文件注册到全局使用,全局使用的文件main.js文件
import { useMessageBox} from '@/ynycComponents/YnycMessageBox/useFun.js'
//全局方法挂载
Vue.prototype.$useMessageBox = useMessageBox;
到这里就已解完成了,剩下的就要到页面使用 js方法中使用
this.$useMessageBox('是否确认该操作','提示',{type:'error'}).then(()=>{
console.log('成功回调')
}).catch(()=>{失败回调})
最终实现的弹框样式结果如下