业务需要实现一个能够自定义内容的confirm弹框, 决定在elementUI dialog基础上封装实现。记录下实现步骤
封装组件
- 首先基于dialog组件封装一个组件
- 使用渲染函数可以接收
export default {
name: 'CustomConfirm',
props: {
message: String | Object,
title: String | Object,
options: Object,
resolveFn: Function,
rejectFn: Function,
},
data() {
return {
visible: true,
};
},
methods: {
confirm() {
this.visible = false;
this.resolveFn();
},
cancel() {
this.visible = false;
this.rejectFn = false;
},
},
render(h) {
return (
<el-dialog visible={this.visible} width='400px' before-close={this.cancel}>
<span slot='title'>{this.title}</span>
<span>{this.message}</span>
<span slot='footer' class='dialog-footer'>
<el-button onclick={this.cancel}>取 消</el-button>
<el-button type='primary' onclick={this.confirm}>
确 定
</el-button>
</span>
</el-dialog>
);
},
};
注册组件
-
实现和elementui中$comfirm的调用形式
a. 为了能够以全局函数的形式调用, 将其以函数形式挂载到Vue原型上 b. 以promise的形式返回
Vue.prototype.$customConfirm= (message, title, options) => {
let div = document.getElementById('custom-confirm');
if (!div) {
div = document.createElement('div');
document.body.appendChild(div);
div.id = 'custom-confirm';
}
const TipConstructor = Vue.extend(CustomConfirm)
const p = new Promise((resolve, reject) => {
const instance = new TipConstructor({
propsData: {
title,
message,
options,
resolveFn: resolve,
rejectFn: reject
}
});
instance.$mount(div);
})
return p;
}
调用方式
- 实现title和mssage内容自定义支持VNode、String类型
this.$customConfirm(
<span>
<i class='iconfont test'></i>
</span>,
<span>
此操作会删除登录账号,是否确认<span class='text-highli'>删除账号</span>?
</span>,
{
type: 'warning',
},
)
.then(() => {})
.catch(() => {});