UNPKG

@ithinkdt/core

Version:

iThinkDT Core

70 lines (63 loc) 1.49 kB
import { onUnmounted, markRaw, toRef, reactive, onDeactivated, onActivated, inject, isRef, watch, shallowReactive, } from 'vue' export const modals = shallowReactive([]) export function useModal(options) { const $options = reactive({ width: 500, ...options, maskClosable: options.maskClosable ?? false, content: markRaw(options.content), inModal: true, }) const key = Symbol() $options[key] = true modals.push($options) onUnmounted(() => { $options.close?.() const index = modals.findIndex((it) => it[key]) if (index !== -1) { modals.splice(index, 1) } }) let lastVisible onActivated(() => { if (lastVisible) $options.show?.() }) onDeactivated(() => { lastVisible = $options.visible if (lastVisible) $options.hide?.() }) return { visible: toRef($options, 'visible'), show: () => $options.show(), hide: () => $options.hide(), close: () => $options.close(), } } export function useModalRef(title) { const modal = inject( '__modal', () => ({ inModal: false, }), true, ) if (title) { if (typeof title === 'string') { modal.title = title } else if (isRef(title)) { watch(title, (t) => (modal.title = t), { immediate: true }) } } return modal }