PetVarietyDialog.vue 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <script setup lang="ts">
  2. import { type CreateProductRequest, type Product } from '@/model/product'
  3. import { type FormInstanceFunctions, type FormRules, MessagePlugin } from 'tdesign-vue-next'
  4. import { createPetVariety, editPetVariety } from '@/api/petVariety'
  5. const props = defineProps<{
  6. data: Product | null
  7. }>()
  8. const formData = ref<{
  9. name: string
  10. }>({
  11. name: ''
  12. })
  13. watch(
  14. () => props.data,
  15. (newData) => {
  16. if (newData) {
  17. formData.value = newData
  18. }
  19. }
  20. )
  21. const rules: FormRules<CreateProductRequest> = {
  22. name: [
  23. {
  24. required: true,
  25. message: '品种名称不能为空'
  26. }
  27. ],
  28. }
  29. const formRef = ref<FormInstanceFunctions | null>(null)
  30. const emits = defineEmits<{
  31. success: [void]
  32. }>()
  33. const editId = computed(() => props.data?.id)
  34. const handleSave = async () => {
  35. const validate = await formRef.value?.validate()
  36. if (validate !== true) return
  37. try {
  38. editId.value
  39. ? await editPetVariety(editId.value, formData.value.name)
  40. : await createPetVariety(formData.value.name)
  41. await MessagePlugin.success(`${editId.value ? '编辑' : '创建'}成功`)
  42. emits('success')
  43. } finally {
  44. formRef.value?.reset()
  45. }
  46. }
  47. </script>
  48. <template>
  49. <TDialog @confirm="handleSave">
  50. <TForm ref="formRef" :data="formData" :rules="rules" resetType="initial">
  51. <TFormItem label="宠物品种名称" name="name">
  52. <TInput v-model.trim="formData.name" clearable placeholder="请输入宠物品种名称" />
  53. </TFormItem>
  54. </TForm>
  55. </TDialog>
  56. </template>
  57. <style scoped></style>