pnpm install lodash-es --save
分类: Vue3标签: Vue, Vue3
日期: 2025/7/6
pnpm install lodash-es --save
首先定义一个子组件my-component
<template>
<view class="dddd"></view>
</template>
import {
createApp,
h,
ref,
Component,
ComponentInternalInstance
} from 'vue';
import AddDialog from './AddDialog.vue';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
/**
* 打开添加对话框
* @param currentInstance - 当前组件实例
* @param url - 请求接口地址
* @param title - 对话框标题
* @param config - 表单配置
*/
export const openAddDialog = (currentInstance: ComponentInternalInstance | null, url: string, title: string, config: any[]) => {
// 创建用于挂载对话框的容器
const container = document.createElement('div');
document.body.appendChild(container);
const parentApp = currentInstance?.appContext.app;
// 定义对话框组件引用
const dialogRef = ref<InstanceType<typeof AddDialog>>();
// 创建 Vue 应用实例
const app = createApp({
setup() {
// 渲染 AddDialog 组件
return () => h(AddDialog, {
ref: dialogRef,
title,
url,
config,
onClose: () => {
destroyDialog();
}
});
}
});
if (parentApp) {
// 继承全局属性
Object.assign(app.config.globalProperties, parentApp.config.globalProperties);
// 继承局部注册组件
if (currentInstance) {
// @ts-ignore 绕过 TypeScript 类型检查,获取内部组件定义
const localComponents = currentInstance.type?.components || {};
for (const [name, component] of Object.entries(localComponents)) {
app.component(name, component as Component);
}
}
}
// 在应用实例中注册 Element Plus
app.use(ElementPlus);
// 定义销毁对话框的方法
const destroyDialog = () => {
app.unmount();
document.body.removeChild(container);
};
// 挂载应用实例
app.mount(container);
// 打开对话框
if (dialogRef.value) {
dialogRef.value.open();
}
return {
destroy: destroyDialog
};
};