useTableCrud.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import { computed, ref } from 'vue';
  2. import { cloneDeep } from 'lodash';
  3. const ACTIONS = {
  4. edit: '编辑',
  5. add: '新增',
  6. };
  7. export default function (
  8. { name, doCreate, doUpdate, refresh, initForm = {} },
  9. formDialogRef
  10. ) {
  11. const saveInitForm = cloneDeep(initForm);
  12. const visible = ref(false);
  13. const type = ref('');
  14. const title = computed(() => ACTIONS[type.value] + name);
  15. const loading = ref(false);
  16. let formRef = ref(null);
  17. const formData = ref({ ...initForm });
  18. //新增
  19. function handleAdd() {
  20. type.value = 'add';
  21. visible.value = true;
  22. formData.value = cloneDeep(saveInitForm);
  23. }
  24. //编辑
  25. function handleEdit(row) {
  26. type.value = 'edit';
  27. visible.value = true;
  28. formData.value = { ...row };
  29. }
  30. //保存
  31. function handleSave() {
  32. if (!['edit', 'add'].includes(type.value)) {
  33. visible.value = false;
  34. return;
  35. }
  36. if (formDialogRef) {
  37. formRef = formDialogRef.value.formRef;
  38. }
  39. formRef?.validate().then(async (res) => {
  40. if (res !== true) return;
  41. const actions = {
  42. add: {
  43. api: () => doCreate(formData.value),
  44. cb: () => $message.success('新增成功'),
  45. },
  46. edit: {
  47. api: () => doUpdate(formData.value),
  48. cb: () => $message.success('编辑成功'),
  49. },
  50. };
  51. const action = actions[type.value];
  52. try {
  53. loading.value = true;
  54. const data = await action.api();
  55. action.cb();
  56. loading.value = visible.value = false;
  57. refresh(data);
  58. } catch (error) {
  59. loading.value = false;
  60. }
  61. });
  62. }
  63. //删除
  64. // function handleDelete(id, confirmOptions) {
  65. // if (!id) return;
  66. // $dialog.confirm({
  67. // content: '确定删除?',
  68. // title: '提示',
  69. // async confirm() {
  70. // try {
  71. // loading.value = true;
  72. // const data = await doDelete(id);
  73. // $message.success('删除成功');
  74. // loading.value = false;
  75. // refresh(data);
  76. // } catch (error) {
  77. // loading.value = false;
  78. // }
  79. // },
  80. // ...confirmOptions,
  81. // });
  82. // }
  83. return {
  84. visible,
  85. type,
  86. title,
  87. loading,
  88. handleAdd,
  89. // handleDelete,
  90. handleEdit,
  91. handleSave,
  92. formData,
  93. formRef,
  94. };
  95. }