Blame view

src/utils/factory/createAsyncComponent.tsx 1.92 KB
1
2
3
4
import {
  defineAsyncComponent,
  // FunctionalComponent, CSSProperties
} from 'vue';
vben authored
5
import { Spin } from 'ant-design-vue';
vben authored
6
import { noop } from '/@/utils/index';
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

// const Loading: FunctionalComponent<{ size: 'small' | 'default' | 'large' }> = (props) => {
//   const style: CSSProperties = {
//     position: 'absolute',
//     display: 'flex',
//     justifyContent: 'center',
//     alignItems: 'center',
//   };
//   return (
//     <div style={style}>
//       <Spin spinning={true} size={props.size} />
//     </div>
//   );
// };
vben authored
22
23
24
25
26
27
28
interface Options {
  size?: 'default' | 'small' | 'large';
  delay?: number;
  timeout?: number;
  loading?: boolean;
  retry?: boolean;
}
vben authored
29
vben authored
30
export function createAsyncComponent(loader: Fn, options: Options = {}) {
31
  const { size = 'small', delay = 100, timeout = 30000, loading = false, retry = true } = options;
vben authored
32
  return defineAsyncComponent({
vben authored
33
34
    loader,
    loadingComponent: loading ? <Spin spinning={true} size={size} /> : undefined,
vben authored
35
36
    // The error component will be displayed if a timeout is
    // provided and exceeded. Default: Infinity.
37
    // TODO
vben authored
38
    timeout,
39
    // errorComponent
vben authored
40
41
    // Defining if component is suspensible. Default: true.
    // suspensible: false,
vben authored
42
    delay,
vben authored
43
44
45
46
47
48
49
    /**
     *
     * @param {*} error Error message object
     * @param {*} retry A function that indicating whether the async component should retry when the loader promise rejects
     * @param {*} fail  End of failure
     * @param {*} attempts Maximum allowed retries number
     */
vben authored
50
51
52
53
54
55
56
57
58
59
60
61
    onError: !retry
      ? noop
      : (error, retry, fail, attempts) => {
          if (error.message.match(/fetch/) && attempts <= 3) {
            // retry on fetch errors, 3 max attempts
            retry();
          } else {
            // Note that retry/fail are like resolve/reject of a promise:
            // one of them must be called for the error handling to continue.
            fail();
          }
        },
vben authored
62
63
  });
}