Browse Source

fix(deepMerge): the default merge strategy

main
xingyu 2 years ago
parent
commit
08d7738f68
  1. 55
      src/utils/index.ts

55
src/utils/index.ts

@ -1,7 +1,7 @@
import type { App, Component } from 'vue' import type { App, Component } from 'vue'
import type { RouteLocationNormalized, RouteRecordNormalized } from 'vue-router' import type { RouteLocationNormalized, RouteRecordNormalized } from 'vue-router'
import { cloneDeep, mergeWith, uniq } from 'lodash-es' import { intersectionWith, isEqual, mergeWith, unionWith } from 'lodash-es'
import { unref } from 'vue' import { unref } from 'vue'
import { isArray, isObject } from '@/utils/is' import { isArray, isObject } from '@/utils/is'
@ -34,21 +34,50 @@ export function setObjToUrlParams(baseUrl: string, obj: any): string {
} }
/** /**
*
* Recursively merge two objects. * Recursively merge two objects.
* @param target The target object to merge into. *
* @param source The source object to merge from. *
* @returns The merged object. * @param source The source object to merge from.
* @param target The target object to merge into.
* @param mergeArrays How to merge arrays. Default is "replace".
* replace
* - "union": Union the arrays.
* - "intersection": Intersect the arrays.
* - "concat": Concatenate the arrays.
* - "replace": Replace the source array with the target array.
* @returns The merged object.
*/ */
export function deepMerge<T extends object | null | undefined, U extends object | null | undefined>(target: T, source: U): T & U { export function deepMerge<T extends object | null | undefined, U extends object | null | undefined>(
return mergeWith(cloneDeep(target), source, (objValue, srcValue) => { source: T,
if (isObject(objValue) && isObject(srcValue)) { target: U,
return mergeWith(cloneDeep(objValue), srcValue, (prevValue, nextValue) => { mergeArrays: 'union' | 'intersection' | 'concat' | 'replace' = 'replace'
// 如果是数组,合并数组(去重) If it is an array, merge the array (remove duplicates) ): T & U {
return isArray(prevValue) ? uniq(prevValue, nextValue) : undefined if (!target) {
}) return source as T & U
} }
}) if (!source) {
return target as T & U
}
if (isArray(target) && isArray(source)) {
switch (mergeArrays) {
case 'union':
return unionWith(target, source, isEqual) as T & U
case 'intersection':
return intersectionWith(target, source, isEqual) as T & U
case 'concat':
return target.concat(source) as T & U
case 'replace':
return source as T & U
default:
throw new Error(`Unknown merge array strategy: ${mergeArrays}`)
}
}
if (isObject(target) && isObject(source)) {
return mergeWith({}, target, source, (targetValue, sourceValue) => {
return deepMerge(targetValue, sourceValue, mergeArrays)
}) as T & U
}
return source as T & U
} }
export function openWindow(url: string, opt?: { target?: TargetContext | string; noopener?: boolean; noreferrer?: boolean }) { export function openWindow(url: string, opt?: { target?: TargetContext | string; noopener?: boolean; noreferrer?: boolean }) {