Skip to content

Commit 9d446aa

Browse files
committed
feat: allow to pass vfm instance as an second argument of useModal for using it outside of script setup syntax
1 parent cf6d100 commit 9d446aa

File tree

2 files changed

+17
-13
lines changed

2 files changed

+17
-13
lines changed

packages/vue-final-modal/src/Modal.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ export type UseModalReturnType<ModalProps extends ComponentProps, DefaultSlotPro
4040
open: () => Promise<string>
4141
close: () => Promise<string>
4242
patchOptions: (options: UseModalOptions<ModalProps, DefaultSlotProps>) => void
43+
destroy: () => void
4344
}
4445

4546
export type Vfm = {

packages/vue-final-modal/src/useApi.ts

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,10 @@ export function useInternalVfm(): InternalVfm {
2121
/**
2222
* Define a dynamic modal.
2323
*/
24-
export function defineModal<
24+
function defineModal<
2525
ModalProps extends ComponentProps,
2626
DefaultSlotProps extends ComponentProps = {},
27-
>(_options?: UseModalOptions<ModalProps, DefaultSlotProps>): UseModalReturnType<ModalProps, DefaultSlotProps> {
27+
>(_options: UseModalOptions<ModalProps, DefaultSlotProps>, vfm: Vfm): UseModalReturnType<ModalProps, DefaultSlotProps> {
2828
const options = reactive({
2929
id: Symbol('useModal'),
3030
modelValue: false,
@@ -57,32 +57,35 @@ export function defineModal<
5757
Object.assign(options?.slots || {}, _options?.slots || {})
5858
}
5959

60+
function destroy(): void {
61+
const index = vfm.dynamicModals.indexOf(options)
62+
if (index !== -1)
63+
vfm.dynamicModals.splice(index, 1)
64+
}
65+
6066
return {
6167
options,
6268
open,
6369
close,
6470
patchOptions,
71+
destroy,
6572
}
6673
}
6774

6875
/**
6976
* Create a dynamic modal.
7077
*/
7178
export function useModal<
72-
ModalProps extends ComponentProps,
73-
DefaultSlotProps extends ComponentProps = {},
74-
>(_options?: UseModalOptions<ModalProps, DefaultSlotProps>): UseModalReturnType<ModalProps, DefaultSlotProps> {
75-
const { dynamicModals } = useVfm()
79+
ModalProps extends ComponentProps,
80+
DefaultSlotProps extends ComponentProps = {},
81+
>(_options: UseModalOptions<ModalProps, DefaultSlotProps>, vfm?: Vfm): UseModalReturnType<ModalProps, DefaultSlotProps> {
82+
const _vfm: Vfm = vfm || useVfm()
7683

77-
const modal = defineModal(_options)
84+
const modal = defineModal(_options, _vfm)
7885

79-
dynamicModals.push(modal.options)
86+
_vfm.dynamicModals.push(modal.options)
8087

81-
onUnmounted(() => {
82-
const index = dynamicModals.indexOf(modal.options)
83-
if (index !== -1)
84-
dynamicModals.splice(index, 1)
85-
})
88+
onUnmounted(() => modal.destroy())
8689

8790
return modal
8891
}

0 commit comments

Comments
 (0)