Blame view

src/utils/index.ts 4.49 KB
1
import type { RouteLocationNormalized, RouteRecordNormalized } from 'vue-router';
2
import type { App, Component } from 'vue';
3
4
import { intersectionWith, isEqual, mergeWith, unionWith } from 'lodash-es';
vben authored
5
import { unref } from 'vue';
6
import { isArray, isObject } from '/@/utils/is';
7
vben authored
8
export const noop = () => {};
Vben authored
9
陈文彬 authored
10
11
12
13
/**
 * @description:  Set ui mount node
 */
export function getPopupContainer(node?: HTMLElement): HTMLElement {
14
  return (node?.parentNode as HTMLElement) ?? document.body;
陈文彬 authored
15
}
vben authored
16
陈文彬 authored
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
 * 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(/&$/, '');
33
  return /\?$/.test(baseUrl) ? baseUrl + parameters : baseUrl.replace(/\/?$/, '?') + parameters;
陈文彬 authored
34
35
}
36
/**
37
38
39
40
41
42
43
44
45
46
47
48
 * Recursively merge two objects.
 * 递归合并两个对象。
 *
 * @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. 合并后的对象。
49
50
 */
export function deepMerge<T extends object | null | undefined, U extends object | null | undefined>(
51
52
53
  source: T,
  target: U,
  mergeArrays: 'union' | 'intersection' | 'concat' | 'replace' = 'replace',
54
): T & U {
55
56
57
58
59
60
  if (!target) {
    return source as T & U;
  }
  if (!source) {
    return target as T & U;
  }
61
62
63
64
65
66
67
68
69
70
71
72
73
74
  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}`);
      }
75
    }
76
77
78
79
80
    if (isObject(targetValue) && isObject(sourceValue)) {
      return deepMerge(sourceValue, targetValue, mergeArrays);
    }
    return undefined;
  });
陈文彬 authored
81
82
}
vben authored
83
84
export function openWindow(
  url: string,
vben authored
85
  opt?: { target?: TargetContext | string; noopener?: boolean; noreferrer?: boolean },
vben authored
86
87
88
89
90
91
92
93
94
) {
  const { target = '__blank', noopener = true, noreferrer = true } = opt || {};
  const feature: string[] = [];

  noopener && feature.push('noopener=yes');
  noreferrer && feature.push('noreferrer=yes');

  window.open(url, target, feature.join(','));
}
vben authored
95
96

// dynamic use hook props
luocong2016 authored
97
export function getDynamicProps<T extends Record<string, unknown>, U>(props: T): Partial<U> {
vben authored
98
99
100
101
102
103
104
105
  const ret: Recordable = {};

  Object.keys(props).map((key) => {
    ret[key] = unref((props as Recordable)[key]);
  });

  return ret as Partial<U>;
}
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
export function getRawRoute(route: RouteLocationNormalized): RouteLocationNormalized {
  if (!route) return route;
  const { matched, ...opt } = route;
  return {
    ...opt,
    matched: (matched
      ? matched.map((item) => ({
          meta: item.meta,
          name: item.name,
          path: item.path,
        }))
      : undefined) as RouteRecordNormalized[],
  };
}
121
luocong2016 authored
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
// https://github.com/vant-ui/vant/issues/8302
type EventShim = {
  new (...args: any[]): {
    $props: {
      onClick?: (...args: any[]) => void;
    };
  };
};

export type WithInstall<T> = T & {
  install(app: App): void;
} & EventShim;

export type CustomComponent = Component & { displayName?: string };

export const withInstall = <T extends CustomComponent>(component: T, alias?: string) => {
  (component as Record<string, unknown>).install = (app: App) => {
    const compName = component.name || component.displayName;
    if (!compName) return;
    app.component(compName, component);
142
143
144
145
    if (alias) {
      app.config.globalProperties[alias] = component;
    }
  };
luocong2016 authored
146
  return component as WithInstall<T>;
147
};