useCreate.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import http from '/admin/support/http'
  2. import { ref, unref, watch } from 'vue'
  3. import { Code } from '/admin/enum/app'
  4. import Message from '/admin/support/message'
  5. import { FormInstance } from 'element-plus'
  6. import { AxiosResponse } from 'axios'
  7. import { isFunction } from '/admin/support/helper'
  8. // get table list
  9. export function useCreate(path: string, id: string | number | null = null, _formData: object = {}) {
  10. const formData = ref<object>(_formData)
  11. const loading = ref<boolean>()
  12. const isClose = ref<boolean>(false)
  13. // 创建前 hook
  14. const beforeCreate = ref()
  15. // 更新前 hook
  16. const beforeUpdate = ref()
  17. const afterCreate = ref()
  18. const afterUpdate = ref()
  19. // store
  20. function store(path: string, id: string | number | null = null) {
  21. loading.value = true
  22. let promise: Promise<AxiosResponse> | null = null
  23. if (id) {
  24. if (isFunction(beforeUpdate.value)) {
  25. beforeUpdate.value()
  26. }
  27. promise = http.put(path + '/' + id, unref(formData))
  28. } else {
  29. if (isFunction(beforeCreate.value)) {
  30. beforeCreate.value()
  31. }
  32. promise = http.post(path, unref(formData))
  33. }
  34. promise
  35. .then(r => {
  36. if (r.data.code === Code.SUCCESS) {
  37. isClose.value = true
  38. Message.success(r.data.message)
  39. // 创建后的操作
  40. if (!id && isFunction(afterCreate.value)) {
  41. afterCreate.value()
  42. }
  43. // 更新后的操作
  44. if (id && isFunction(afterUpdate.value)) {
  45. afterUpdate.value()
  46. }
  47. } else {
  48. Message.error(r.data.message)
  49. }
  50. })
  51. .finally(() => {
  52. loading.value = false
  53. })
  54. }
  55. const form = ref<FormInstance>()
  56. const submitForm = (formEl: FormInstance | undefined) => {
  57. if (!formEl) return
  58. formEl
  59. .validate(valid => {
  60. if (valid) {
  61. store(path, id)
  62. } else {
  63. loading.value = false
  64. }
  65. })
  66. .then(() => {})
  67. }
  68. const close = (func: Function) => {
  69. watch(isClose, function (value) {
  70. if (value && isFunction(func)) {
  71. func()
  72. }
  73. })
  74. }
  75. return { formData, loading, form, submitForm, close, beforeCreate, beforeUpdate, afterCreate, afterUpdate }
  76. }