vue+ts项目 封装element-ui的messagebox

场景

问题: 有一个在项目非常常用的确认弹框, 并且使用element-ui的 messageBox;
我们不想在每一业务中大量的复制那么多的代码,
解决办法: 封装一个函数调用,尽可能给出操作回调

代码
代码连接 github
import {MessageBox} from 'element-ui';
Vue.prototype.$msgbox = MessageBox;

//msgbox.ts

function msgbox(
	vm: any,
	title: string = '消息',
	text: string,
	smallText: string = '',
	isClose: boolean = false,
	callback?: any,
	success?: any,
	cancel?: any,
	smallStyle: string = 'color: #cacaca',
) {
	const h = vm.$createElement;
	vm.$msgbox({
		title: title,
		message: h('div', null, [
			h('p', null, text),
			h('span', {style: smallStyle}, smallText)
		]),
		// distinguishCancelAndClose: false,
		closeOnClickModal: false,
		closeOnPressEscape: false,
		showClose: isClose,
		showCancelButton: true,
		cancelButtonText: '取消',
		confirmButtonText: '移除',
		cancelButtonClass: 'msgbox-btn msgbox-float-r',
		confirmButtonClass: 'msgbox-btn msgbox-mr20',
		beforeClose: (action: any, instance: any, done: any) => {
			if (action === 'confirm') {
				if (typeof callback === 'function') {
					callback(action, instance, done);
				} else {
					throw new class implements Error {
						public message: string = 'callback is not function';
						public name: string = 'beforeClose';
					};
				}
			} else {
				done();
			}
		}
	}).then((action: any): void => {
		if (typeof success === 'function') {
			success(action);
		} else {
			throw new class implements Error {
				public message: string = 'callback is not function';
				public name: string = 'confirm';
			};
		}
	}).catch((action: any) => {
		if (typeof cancel === 'function') {
			cancel(action);
		} else {
			throw new class implements Error {
				public message: string = 'callback is not function';
				public name: string = 'cancel';
			};
		}
	});
}

export default msgbox;

你可能感兴趣的:(vue)