refactor: deepMerge
parent
f56231cc10
commit
2989bbded0
|
@ -2,8 +2,8 @@ import type { RouteLocationNormalized, RouteRecordNormalized } from 'vue-router'
|
||||||
import type { App, Component } from 'vue'
|
import type { App, Component } from 'vue'
|
||||||
|
|
||||||
import { unref } from 'vue'
|
import { unref } from 'vue'
|
||||||
import { isObject } from '@/utils/is'
|
import { isArray, isObject } from '@/utils/is'
|
||||||
import { cloneDeep } from 'lodash-es'
|
import { cloneDeep, mergeWith } from 'lodash-es'
|
||||||
|
|
||||||
export const noop = () => {}
|
export const noop = () => {}
|
||||||
|
|
||||||
|
@ -33,14 +33,21 @@ export function setObjToUrlParams(baseUrl: string, obj: any): string {
|
||||||
return /\?$/.test(baseUrl) ? baseUrl + parameters : baseUrl.replace(/\/?$/, '?') + parameters
|
return /\?$/.test(baseUrl) ? baseUrl + parameters : baseUrl.replace(/\/?$/, '?') + parameters
|
||||||
}
|
}
|
||||||
|
|
||||||
// 深度合并
|
/**
|
||||||
export function deepMerge<T = any>(src: any = {}, target: any = {}): T {
|
* 递归合并两个对象。
|
||||||
let key: string
|
* Recursively merge two objects.
|
||||||
const res: any = cloneDeep(src)
|
* @param target 目标对象,合并后结果存放于此。The target object to merge into.
|
||||||
for (key in target) {
|
* @param source 要合并的源对象。The source object to merge from.
|
||||||
res[key] = isObject(res[key]) ? deepMerge(res[key], target[key]) : target[key]
|
* @returns 合并后的对象。The merged object.
|
||||||
}
|
*/
|
||||||
return res
|
export function deepMerge<T extends object | null | undefined, U extends object | null | undefined>(target: T, source: U): T & U {
|
||||||
|
return mergeWith(cloneDeep(target), source, (objValue, srcValue) => {
|
||||||
|
if (isObject(objValue) && isObject(srcValue)) {
|
||||||
|
return mergeWith(cloneDeep(objValue), srcValue, (prevValue, nextValue) => {
|
||||||
|
return isArray(prevValue) ? prevValue.concat(nextValue) : undefined
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
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 }) {
|
||||||
|
|
Loading…
Reference in New Issue