createAsyncComponent.tsx 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { defineAsyncComponent } from 'vue';
  2. import { Spin } from 'ant-design-vue';
  3. import { noop } from '/@/utils/index';
  4. interface Options {
  5. size?: 'default' | 'small' | 'large';
  6. delay?: number;
  7. timeout?: number;
  8. loading?: boolean;
  9. retry?: boolean;
  10. }
  11. export function createAsyncComponent(loader: Fn, options: Options = {}) {
  12. const { size = 'small', delay = 100, timeout = 3000, loading = true, retry = true } = options;
  13. return defineAsyncComponent({
  14. loader,
  15. loadingComponent: loading ? <Spin spinning={true} size={size} /> : undefined,
  16. // The error component will be displayed if a timeout is
  17. // provided and exceeded. Default: Infinity.
  18. timeout,
  19. // Defining if component is suspensible. Default: true.
  20. // suspensible: false,
  21. delay,
  22. /**
  23. *
  24. * @param {*} error Error message object
  25. * @param {*} retry A function that indicating whether the async component should retry when the loader promise rejects
  26. * @param {*} fail End of failure
  27. * @param {*} attempts Maximum allowed retries number
  28. */
  29. onError: !retry
  30. ? noop
  31. : (error, retry, fail, attempts) => {
  32. if (error.message.match(/fetch/) && attempts <= 3) {
  33. // retry on fetch errors, 3 max attempts
  34. retry();
  35. } else {
  36. // Note that retry/fail are like resolve/reject of a promise:
  37. // one of them must be called for the error handling to continue.
  38. fail();
  39. }
  40. },
  41. });
  42. }