vue3.2+ts如何实现在方法中可调用的拟态框弹窗
直接上图。

解决代码如下:
import { createApp } from 'vue'
import MessageBoxVue from './MessageBox.vue' \你写的拟态框样式
export const MessageBox = (text: any) => {
return new Promise((resolve, reject) => {
const capp = createApp(MessageBoxVue, text)
const container = document.createElement('div')
const instance = capp.mount(container)
document.body.insertBefore(container, document.body.firstChild)//插入到body最前面,层级更高
instance.callback = (val: any) => {
if (val) {
resolve(val)
} else {
reject()
}
capp.unmount()//注销
document.body.removeChild(container)//点击后清除弹窗
}
instance.close = () => {
capp.unmount()
document.body.removeChild(container)
}
})
}//重点在这儿
//这边相当于把数据当方法使了。我也不知道什么原理。在上面那边就是能接收到回调。
const cancel = () => {
callback.value(false)
}
const confirm = () => {
callback.value(true)
}
const closeBox = () => {
close.value()
}
//抛出这两个方法?反正这个方法不可或缺。
defineExpose({
callback,
close
})\这一段是上面的那个messagebox{{ title }}{{ content }}
{{ cancelVal }} {{ confirmVal }}
引入全局后的调用
// 使用:
// 在main.ts全局引入,也可以按需引入这里展示全局引入
import {MessageBox} from 'base/src/components/MessageBox/index'
// 注册:
app.config.globalProperties.$messageBox = MessageBox
// 引用:
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
const fn = ()=>{
proxy
.$messageBox({
//这边就是传你在MessageBox的props定义的父传子的数据了
title: '是否确定编辑/删除数据?',
content: '作业已经发布,如果重新编辑/删除,会清空所有学生 作业提交状态请谨慎操作!'
})
.then(() => {
console.log(1234)
})
.catch(() => {
console.log(12345)
})
}