wupengfei
2025-12-03 fa5ee26bb701b816efc811c193ee55504a6efd51
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { computed, reactive } from 'vue';
import { cloneDeep } from 'lodash';
 
type UseDialogOptions = {
  onConfirm?: (...args: any) => Promise<any>;
  closeAfterConfirm?: boolean;
};
 
export function useDialog(options: UseDialogOptions = {}) {
  const { onConfirm, closeAfterConfirm = true } = options;
 
  const dialogState = reactive({
    dialogVisible: false,
  });
 
  function onUpdateModelValue(value: boolean) {
    dialogState.dialogVisible = value;
  }
 
  async function handleConfirm(...args: any) {
    await onConfirm?.(...args);
    if (closeAfterConfirm) {
      dialogState.dialogVisible = false;
    }
  }
 
  const dialogProps = computed(() => ({
    modelValue: dialogState.dialogVisible,
    ['onUpdate:modelValue']: onUpdateModelValue,
    onOnConfirm: handleConfirm,
  }));
 
  return {
    dialogProps,
    dialogState,
  };
}
 
export type FormParams = {};
 
type UseFormDialogOptions<TFormParams extends FormParams> = UseDialogOptions & {
  defaultFormParams: TFormParams;
};
 
export function useFormDialog<TFormParams extends FormParams>(
  options: UseFormDialogOptions<TFormParams>
) {
  const { onConfirm, closeAfterConfirm = true, defaultFormParams } = options;
  const { dialogProps, dialogState } = useDialog({ onConfirm, closeAfterConfirm });
 
  const editForm = reactive(cloneDeep(defaultFormParams));
 
  function handleAdd(extraParams: Partial<TFormParams> = {}) {
    Object.assign(editForm, cloneDeep(defaultFormParams), {
      ...extraParams,
    });
    dialogState.dialogVisible = true;
  }
 
  function handleEdit(data: Omit<TFormParams, 'title'>) {
    Object.assign(editForm, cloneDeep(defaultFormParams), {
      ...data,
    });
    dialogState.dialogVisible = true;
  }
 
  function onUpdateForm(value: TFormParams) {
    Object.assign(editForm, value);
  }
 
  const formDialogProps = computed(() => ({
    ...dialogProps.value,
    form: editForm,
    ['onUpdate:form']: onUpdateForm,
  }));
 
  return {
    dialogProps: formDialogProps,
    dialogState,
    editForm,
    handleAdd,
    handleEdit,
  };
}