huangyinfeng
4 天以前 db42d08c39ae6129e2b95cd24c0d57c6769282e5
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
import type { Ref } from 'vue';
import { unref } from 'vue';
import { tryOnUnmounted } from '@vueuse/core';
import { createLoading } from './createLoading';
import type { LoadingProps } from './typing';
 
export interface UseLoadingOptions {
  target?: any;
  props?: Partial<LoadingProps>;
}
 
interface Fn {
  (): void;
}
 
export function useLoading(props: Partial<LoadingProps>): [Fn, Fn, (string) => void];
export function useLoading(opt: Partial<UseLoadingOptions>): [Fn, Fn, (string) => void];
 
export function useLoading(
  opt: Partial<LoadingProps> | Partial<UseLoadingOptions>,
): [Fn, Fn, (string) => void] {
  let props: Partial<LoadingProps>;
  let target: HTMLElement | Ref<ElRef> = document.body;
 
  if (Reflect.has(opt, 'target') || Reflect.has(opt, 'props')) {
    const options = opt as Partial<UseLoadingOptions>;
    props = options.props || {};
    target = options.target || document.body;
  } else {
    props = opt as Partial<LoadingProps>;
  }
 
  const instance = createLoading(props, undefined, true);
 
  const open = (): void => {
    const t = unref(target as Ref<ElRef>);
    if (!t) return;
    instance.open(t);
  };
 
  const close = (): void => {
    instance.close();
  };
 
  const setTip = (tip: string) => {
    instance.setTip(tip);
  };
 
  tryOnUnmounted(() => {
    instance.destroy();
  });
 
  return [open, close, setTip];
}