index.ts 1.29 KB
Newer Older
qd01's avatar
qd01 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
/* eslint-disable ts/no-use-before-define */
import { h, render } from 'vue'
import XModal from './x-modal.vue'
import type { App } from 'vue'

interface XModalProps {
  visible?: boolean
  title?: string
  content: string
  okText?: string
  onClose?: () => void
  onOk?: () => void
}

function isFunction(obj: any): obj is (...args: any[]) => any {
  return typeof obj === 'function'
}

const Modal = {
  install(app: App) {
    app.component(XModal.name!, XModal)
  },
  open(config: XModalProps) {
    let container: HTMLElement | null = document.createElement('div')

    const handleOk = () => {
      if (vm.component) {
        vm.component.props.visible = false
      }

      if (isFunction(config.onOk)) {
        config.onOk()
      }
    }

    const handleClose = () => {
      if (container) {
        render(null, container)
        document.body.removeChild(container)
      }
      container = null
      if (isFunction(config.onClose)) {
        config.onClose()
      }
    }

    const defaultConfig = {
      visible: true,
      onOk: handleOk,
      onClose: handleClose,
    }

    const vm = h(XModal, {
      ...config,
      ...defaultConfig,
    })

    render(vm, container)
    document.body.appendChild(container)

    return {
      close: handleClose,
    }
  },
}

export default Modal