1. Promise 风格(openModal):
// 原生Promise风格,使用try/catch捕获错误
try {
const result = await ModalManager.openModal(
'CustomModal', // 直接使用组件名,自动懒加载
{
title: 'Promise风格模态框',
modalKey: 'promise_modal'
}
);
// 模态框成功确认
console.log('模态框确认返回数据:', result.data);
this.$message.success('操作成功!');
} catch (error) {
// 捕获取消或错误
if (error.isCanceled) {
console.log('模态框被取消:', error);
this.$message.info('操作已取消');
} else {
console.error('模态框打开失败:', error);
this.$message.error('操作失败!');
}
}
2. Await-to-js 风格(toOpenModal):
// Await-to-js风格,无需try/catch,返回[err, result]
const [err, result] = await ModalManager.toOpenModal(
'CustomModal', // 组件名懒加载
{
title: 'Await-to-js风格模态框',
modalKey: 'await_to_js_modal'
}
);
if (err) {
// 模态框被取消或发生错误
if (err.isCanceled) {
console.log('模态框被取消:', err);
this.$message.info('操作已取消');
} else {
console.error('模态框打开失败:', err);
this.$message.error('操作失败!');
}
} else {
// 模态框成功确认
console.log('模态框确认返回数据:', result.data);
this.$message.success(`操作成功:${result.data.inputValue}`);
}
3. 懒加载组件注册示例:
// 注册懒加载组件
ModalManager.registerLazyComponent('CustomModal', () => {
// 实际项目中可以替换为 import() 动态导入
return Promise.resolve({
// 组件定义
props: { /* ... */ },
template: `/* ... */`,
methods: { /* ... */ }
});
});
// 也可以注册普通组件
ModalManager.registerComponent('SimpleModal', {
props: { /* ... */ },
template: `/* ... */`
});
4. 隐藏/销毁模态框:
// 隐藏模态框(仅隐藏,不销毁实例)
ModalManager.hideModal('modal_id');
// 销毁模态框(完全销毁,释放内存)
ModalManager.destroyModal('modal_id');
5. 内嵌模态框示例(懒加载):
// 在模态框组件内部打开另一个模态框(自动懒加载)
async openNestedModalPromise() {
try {
const result = await ModalManager.openModal(
'NestedModal', // 懒加载内嵌组件
{
title: 'Promise风格内嵌模态框',
modalKey: 'nested_modal_' + this.modalId,
parentModalId: this.modalId
}
);
console.log('内嵌模态框确认:', result.data);
this.$message.success(`内嵌模态框返回: ${JSON.stringify(result.data)}`);
} catch (error) {
if (!error.isCanceled) {
this.$message.error('内嵌模态框操作失败');
}
}
}