在element-plus中,Messagebox和Message都实现了全局方法。但是Dialog就没有实现。
本着自己动手丰衣足食的原则。自己动手写一个。
定义一个ModalService.ts文件
import { h, render } from 'vue'
class ModalService {
/**
* 创建一个弹出框
* @param component 组件
* @param opt 配置
*/
static Create(component: any, props: any, opt?: ModalOption,) {
return new Promise((resolve, reject) => {
const close = () => {
render(null, container)
document.body.removeChild(container);
resolve(true)
}
const modelValue = true
const dialogProps = {
modelValue: modelValue,
title: opt?.title,
draggable: opt?.draggable,
destroyOnClose: true,
onClosed: close,
}
const closeHandler = () => {
if (vNode.component?.props.modelValue) {
vNode.component!.props.modelValue = false
}
}
const container = document.createElement('div')
document.body.appendChild(container)
var vNode = h(ElDialog, dialogProps, {
default: () => {
let type = typeof component;
if (type == 'string' || type == 'number') {
return h('div', component)
} else {
return h(component, {
...props,
onClose: closeHandler
})
}
},
header: () => {
if (dialogProps) {
let type = typeof dialogProps.title
if (type == 'string' || type == 'number') {
return h('span', dialogProps.title)
}
return h(dialogProps.title, null)
}
}
});
render(vNode, container)
return vNode.component;
})
}
}
使用
import HelloWorld from "../../../components/HelloWorld.vue"
const test = () => {
ModalService.Create(HelloWorld, { msg: '传递参数' }, { title: '卧槽' }).then(() => {
console.log('成功关闭')
});
}
当然这只是一个demo,很多el-dialog组件的参数和事件没有考虑到。以后有空再完善了。
标签:const,render,Service,title,dialogProps,component,element,return,type From: https://www.cnblogs.com/boxrice/p/16746406.html