toast.ui.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import type { ToastOptions as VantToastOptions, ToastWrapperInstance as VantToastWrapperInstance } from 'vant';
  2. import { closeToast, showToast } from 'vant';
  3. import 'vant/es/toast/style';
  4. type ToastOptions = Omit<VantToastOptions, 'message'>;
  5. export class Toast {
  6. static show(message: string, options?: ToastOptions) {
  7. const toastRef = showToast({ message, ...options });
  8. return { toastRef, close: () => toastRef.close() };
  9. }
  10. static close() { closeToast(true); }
  11. static success(message: string, options?: ToastOptions) {
  12. return this.show(message, { ...options, closeOnClick: true, closeOnClickOverlay: true, type: 'success' });
  13. }
  14. static warning(message: string, options?: ToastOptions) {
  15. return this.show(message, { ...options, icon: 'warning-o' });
  16. }
  17. static error(message: string, options?: ToastOptions) {
  18. return this.show(message, { ...options, type: 'fail' });
  19. }
  20. static loading(delay = 0, options?: ToastOptions & { message?: string }) {
  21. const fn = () => this.show(options?.message ?? '加载中...', {
  22. ...options,
  23. type: 'loading',
  24. closeOnClick: false,
  25. closeOnClickOverlay: false,
  26. forbidClick: true,
  27. duration: 0,
  28. });
  29. if (delay === 0) { return fn(); }
  30. const timer = setTimeout(() => {
  31. ({ toastRef: ref.toastRef, close: ref.close } = fn());
  32. }, delay);
  33. const ref = {
  34. toastRef: null as VantToastWrapperInstance | null,
  35. cancel: () => clearTimeout(timer),
  36. close: () => clearTimeout(timer),
  37. };
  38. return ref;
  39. }
  40. }