optimize(projects): 动态加载组件方法抽取为公共函数

This commit is contained in:
AN
2025-06-21 13:48:11 +08:00
parent e86a6d1b7a
commit 2f8a6b4b84
2 changed files with 34 additions and 18 deletions

View File

@ -1,5 +1,7 @@
import { defineAsyncComponent, markRaw } from 'vue';
import { AcceptType } from '@/enum/business';
import { $t } from '@/locales';
/**
* Transform record to option
*
@ -76,6 +78,33 @@ export function humpToLine(str: string, line: string = '-') {
return temp;
}
/** 动态加载组件 */
export async function loadDynamicComponent<T extends object = any>(
modules: Record<string, () => Promise<any>>,
formPath: string,
options?: {
delay?: number;
timeout?: number;
}
) {
const expectedPathSuffix = `${humpToLine(formPath)}.vue`;
const matchedKey = Object.keys(modules).find(path => path.endsWith(expectedPathSuffix));
if (!matchedKey) {
window.$message?.error('组件不存在');
throw new Error(`组件不存在: ${expectedPathSuffix}`);
}
return markRaw(
defineAsyncComponent({
loader: async () => (await modules[matchedKey]()) as T,
delay: options?.delay ?? 200,
timeout: options?.timeout ?? 3000
})
);
}
/** 判断是否为空 */
export function isNotNull(value: any) {
return value !== undefined && value !== null && value !== '' && value !== 'undefined' && value !== 'null';