index.ts
2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { isObject } from '@wry-smile/utils-is'
import { intersectionWith, isArray, isEqual, mergeWith, unionWith } from 'lodash-es'
import { unref } from 'vue'
/**
* @description: Set ui mount node
*/
export function getPopupContainer(node?: HTMLElement): HTMLElement {
return (node?.parentNode as HTMLElement) ?? document.body
}
/**
*
* @param source 合并的源对象
* @param target 目标对象, 合并结果存放在此对象中
* @param mergeArrays - 合并策略
* - "union": 并集
* - "intersection": 交集
* - "concat": 连接
* - "replace": 替换
* @returns
*/
export function deepMerge<T extends object | null | undefined, U extends object | null | undefined>(
source: T,
target: U,
mergeArrays: 'union' | 'intersection' | 'concat' | 'replace' = 'replace',
): T & U {
if (!target)
return source as T & U
if (!source)
return target as T & U
return mergeWith({}, source, target, (sourceValue, targetValue) => {
if (isArray(targetValue) && isArray(sourceValue)) {
switch (mergeArrays) {
case 'union':
return unionWith(sourceValue, targetValue, isEqual)
case 'intersection':
return intersectionWith(sourceValue, targetValue, isEqual)
case 'concat':
return sourceValue.concat(targetValue)
case 'replace':
return targetValue
default:
throw new Error(`Unknown merge array strategy: ${mergeArrays as string}`)
}
}
if (isObject(targetValue) && isObject(sourceValue))
return deepMerge(sourceValue, targetValue, mergeArrays)
return undefined
})
}
// dynamic use hook props
export function getDynamicProps<T extends Record<string, unknown>, U>(props: T): Partial<U> {
const ret: Recordable = {}
Object.keys(props).forEach((key) => {
ret[key] = unref((props as Recordable)[key])
})
return ret as Partial<U>
}
/**
* Add the object as a parameter to the URL
* @param baseUrl url
* @param obj
* @returns {string}
* eg:
* let obj = {a: '3', b: '4'}
* setObjToUrlParams('www.baidu.com', obj)
* ==>www.baidu.com?a=3&b=4
*/
export function setObjToUrlParams(baseUrl: string, obj: any): string {
let parameters = ''
for (const key in obj)
parameters += `${key}=${encodeURIComponent(obj[key])}&`
parameters = parameters.replace(/&$/, '')
return /\?$/.test(baseUrl) ? baseUrl + parameters : baseUrl.replace(/\/?$/, '?') + parameters
}