Vue.js弹出模态框组件开发的示例代码

2020-06-14 05:59:29易采站长站整理

computed: {
modal: function() {
let options = this.dialogOption;
return {
title: options.title || '提示',
text: options.text,
cancelButtonText: options.cancelButtonText ? options.cancelButtonText : '取消',
confirmButtonText: options.confirmButtonText ? options.confirmButtonText : '确定',
}
}
},
methods: {
//确定,将promise断定为完成态
submit() {
this.resolve('submit');
},
// 取消,将promise断定为reject状态
cancel() {
this.reject('cancel');
},
//显示confirm弹出,并创建promise对象,给父组件调用
confirm() {
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
return this.promise; //返回promise对象,给父级组件调用
}
}

}

在模态框组件中定义了三个方法,核心的方法是confirm,此方法是提供给父级组件调用的,返回一个promise对象。使用promise对象主要是为了异步调用,因为很多时候我们使用模态框时需要根据返回结果再进行下一步处理。

扩展提示:

如果需要扩展的话,可以通过props的dialogOption传递更多的字段,在computed中进行判断,比如增加一个字段isShowCancelButton可以控制取消按钮是否显示。其他扩展同理。

调用


<v-dialog v-show="showDialog" :dialog-option="dialogOption" ref="dialog"></v-dialog>

this.showDialog = true;
this.$refs.dialog.confirm().then(() => {
this.showDialog = false;
next();
}).catch(() => {
this.showDialog = false;
next();
})

源码地址

Dialog组件源码

实现效果