useModal.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * @Description:
  3. * @Author: qianlishi
  4. * @Date: 2024-12-08 17:38:28
  5. * @LastEditors: qianlishi
  6. * @LastEditTime: 2024-12-13 15:33:45
  7. */
  8. import { ref, unref, getCurrentInstance, watch } from 'vue';
  9. import { isProdMode } from '@/utils/env';
  10. import { ModalMethods, UseModalReturnType } from '../type';
  11. import { getDynamicProps } from '@/utils';
  12. import { tryOnUnmounted } from '@vueuse/core';
  13. export function useModal(props): UseModalReturnType {
  14. const modalRef = ref<Nullable<ModalMethods>>(null);
  15. const currentInstance = getCurrentInstance();
  16. const getInstance = () => {
  17. const instance = unref(modalRef.value);
  18. if (!instance) {
  19. console.error('useModal instance is undefined!');
  20. }
  21. return instance;
  22. };
  23. const register = (modalInstance: ModalMethods) => {
  24. isProdMode() &&
  25. tryOnUnmounted(() => {
  26. modalRef.value = null;
  27. });
  28. modalRef.value = modalInstance;
  29. currentInstance?.emit('register', modalInstance);
  30. watch(
  31. () => props,
  32. () => {
  33. props && modalInstance.setProps(getDynamicProps(props));
  34. },
  35. {
  36. immediate: true,
  37. deep: true,
  38. },
  39. );
  40. };
  41. const methods: ModalMethods = {
  42. setProps: (props): void => {
  43. getInstance()?.setProps(props);
  44. },
  45. openModal: () => {
  46. getInstance()?.openModal();
  47. },
  48. closeModal: () => {
  49. getInstance()?.closeModal();
  50. },
  51. setSubLoading: (status) => {
  52. getInstance()?.setSubLoading(status);
  53. },
  54. };
  55. return [register, methods];
  56. }