import { reactive } from 'vue' /** 组件默认配置存储:组件名 -> 默认 props/配置 */ const componentSettings = reactive>>({}) /** * 深度合并两个对象 * - source 的值会覆盖 target 的值 * - 对于嵌套对象,会递归合并 * - 数组直接替换,不合并 */ function deepMerge(target: Record, source?: Record): Record { if (!source) return target for (const key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { const targetValue = target[key] const sourceValue = source[key] if (key === 'components') { target[key] = { ...(targetValue as Record), ...(sourceValue as Record) } } else if (isPlainObject(sourceValue)) { if (!isPlainObject(targetValue)) { target[key] = { ...(sourceValue as Record) } } else { target[key] = deepMerge( targetValue as Record, sourceValue as Record ) } } else { target[key] = sourceValue } } } return target } /** 判断是否为普通对象(非数组、非 null) */ function isPlainObject(value: unknown): value is Record { if (!value || typeof value !== 'object') return false const proto = Object.getPrototypeOf(value) return proto === Object.prototype || proto === null } export interface UseComponentSettingReturn { /** 获取组件默认配置;不传参时返回全部组件的配置 */ getSetting: = Record>(componentName?: string) => T /** 设置组件默认配置(与已有配置深度合并) */ setSetting: (componentName: string, config: Record) => void /** 合并组件配置:全局配置与组件 props 合并,返回合并后的结果 */ mergeSettings: = Record>(componentName: string, props: Record) => T } /** * 组件默认配置:供所有组件统一获取/设置默认配置 * - getSetting:获取组件默认配置 * - setSetting:设置组件默认配置(深度合并),可在应用入口或按需调用 * - mergeSettings:合并全局配置与组件 props,props 优先级更高 * * 合并优先级:组件默认值 < 全局配置 < 组件 props */ export function useComponentSetting(): UseComponentSettingReturn { /** 返回浅拷贝(仅外层解包),内部保持对 reactive 存储的直接引用,保证响应式追踪 */ const getSetting = = Record>(componentName?: string): T => { if (componentName === undefined) { return { ...componentSettings } as T } return { ...(componentSettings[componentName] ?? {}) } as T } const setSetting = (componentName: string, config: Record): void => { const current = componentSettings[componentName] if (current) { componentSettings[componentName] = deepMerge({ ...current }, config) } else { componentSettings[componentName] = { ...config } } } /** 合并全局配置与组件 props,props 优先级更高 */ const mergeSettings = = Record>(componentName: string, props: Record): T => { const globalSetting = componentSettings[componentName] ?? {} return deepMerge({ ...globalSetting }, props) as T } return { getSetting, setSetting, mergeSettings, } }