feat: modal support destroy on close

This commit is contained in:
Netfan 2024-12-30 20:26:15 +08:00
parent 2eb7fed9f4
commit 4a8e6abc06
2 changed files with 27 additions and 2 deletions

View File

@ -143,6 +143,10 @@ export interface ModalApiOptions extends ModalState {
* *
*/ */
connectedComponent?: Component; connectedComponent?: Component;
/**
* 使 connectedComponent
*/
destroyOnClose?: boolean;
/** /**
* false * false
* @returns * @returns

View File

@ -1,6 +1,14 @@
import type { ExtendedModalApi, ModalApiOptions, ModalProps } from './modal'; import type { ExtendedModalApi, ModalApiOptions, ModalProps } from './modal';
import { defineComponent, h, inject, nextTick, provide, reactive } from 'vue'; import {
defineComponent,
h,
inject,
nextTick,
provide,
reactive,
ref,
} from 'vue';
import { useStore } from '@vben-core/shared/store'; import { useStore } from '@vben-core/shared/store';
@ -18,6 +26,7 @@ export function useVbenModal<TParentModalProps extends ModalProps = ModalProps>(
const { connectedComponent } = options; const { connectedComponent } = options;
if (connectedComponent) { if (connectedComponent) {
const extendedApi = reactive({}); const extendedApi = reactive({});
const isModalReady = ref(true);
const Modal = defineComponent( const Modal = defineComponent(
(props: TParentModalProps, { attrs, slots }) => { (props: TParentModalProps, { attrs, slots }) => {
provide(USER_MODAL_INJECT_KEY, { provide(USER_MODAL_INJECT_KEY, {
@ -27,6 +36,11 @@ export function useVbenModal<TParentModalProps extends ModalProps = ModalProps>(
Object.setPrototypeOf(extendedApi, api); Object.setPrototypeOf(extendedApi, api);
}, },
options, options,
async reCreateModal() {
isModalReady.value = false;
await nextTick();
isModalReady.value = true;
},
}); });
checkProps(extendedApi as ExtendedModalApi, { checkProps(extendedApi as ExtendedModalApi, {
...props, ...props,
@ -35,7 +49,7 @@ export function useVbenModal<TParentModalProps extends ModalProps = ModalProps>(
}); });
return () => return () =>
h( h(
connectedComponent, isModalReady.value ? connectedComponent : 'div',
{ {
...props, ...props,
...attrs, ...attrs,
@ -62,6 +76,13 @@ export function useVbenModal<TParentModalProps extends ModalProps = ModalProps>(
options.onOpenChange?.(isOpen); options.onOpenChange?.(isOpen);
injectData.options?.onOpenChange?.(isOpen); injectData.options?.onOpenChange?.(isOpen);
}; };
mergedOptions.onClosed = () => {
options.onClosed?.();
if (options.destroyOnClose) {
injectData.reCreateModal?.();
}
};
const api = new ModalApi(mergedOptions); const api = new ModalApi(mergedOptions);
const extendedApi: ExtendedModalApi = api as never; const extendedApi: ExtendedModalApi = api as never;