Confirm Delete
import type { InjectionKey, ShallowRef } from 'vue';
import { inject, provide, shallowRef } from 'vue';
interface ConfirmDialog {
isVisible: ShallowRef<boolean>;
message: ShallowRef<string>;
/** open the dialog and resolve with the user's choice */
confirm: (message: string) => Promise<boolean>;
/** resolve the open dialog — wired to the dialog's Confirm/Cancel buttons */
settle: (value: boolean) => void;
}
const DialogKey: InjectionKey<ConfirmDialog> = Symbol('confirm-dialog');
/**
* Scoped confirm dialog. Call `provideConfirmDialog()` once in an ancestor (it returns the instance so that
* same component can use it too) and `useConfirmDialog()` in any descendant.
*/
export function provideConfirmDialog(): ConfirmDialog {
const isVisible = shallowRef(false);
const message = shallowRef('');
let resolveFn: ((value: boolean) => void) | null = null;
function confirm(next: string) {
message.value = next;
isVisible.value = true;
return new Promise<boolean>((resolve) => {
resolveFn = resolve;
});
}
function settle(value: boolean) {
isVisible.value = false;
resolveFn?.(value);
resolveFn = null;
}
const dialog: ConfirmDialog = { isVisible, message, confirm, settle };
provide(DialogKey, dialog);
return dialog;
}
export function useConfirmDialog(): ConfirmDialog {
const dialog = inject(DialogKey);
if (!dialog) {
throw new Error('useConfirmDialog() must be used under a component that called provideConfirmDialog()');
}
return dialog;
}Last updated on