useModal.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { ref, unref, watch } from 'vue';
  2. import { tryOnUnmounted } from '@vueuse/core';
  3. import type { ModalMethods, UseModalReturnType, modalProps } from '../types';
  4. export function useModal(props: modalProps): UseModalReturnType {
  5. const modalRef = ref<Nullable<ModalMethods>>(null);
  6. const getInstance = () => {
  7. const instance = unref(modalRef.value);
  8. if (!instance) {
  9. console.error('useModal instance is undefined!');
  10. }
  11. return instance;
  12. };
  13. const register = (modalInstance: ModalMethods) => {
  14. tryOnUnmounted(() => {
  15. modalRef.value = null;
  16. });
  17. modalRef.value = modalInstance;
  18. watch(
  19. () => props,
  20. () => {
  21. if (props) {
  22. modalInstance.setModalProps(props);
  23. }
  24. },
  25. {
  26. immediate: true,
  27. deep: true
  28. }
  29. );
  30. };
  31. const methods: ModalMethods = {
  32. setModalLoading(status) {
  33. getInstance()?.setModalLoading(status);
  34. },
  35. setModalProps: (newProps: modalProps): void => {
  36. getInstance()?.setModalProps(newProps);
  37. },
  38. openModal: (record?: Recordable) => {
  39. getInstance()?.openModal(record);
  40. },
  41. closeModal: () => {
  42. getInstance()?.closeModal();
  43. },
  44. setSubLoading: status => {
  45. getInstance()?.setSubLoading(status);
  46. }
  47. };
  48. return [register, methods];
  49. }