ProductPropertyAddForm.vue 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <template>
  2. <Dialog v-model="dialogVisible" :title="dialogTitle">
  3. <el-form
  4. ref="formRef"
  5. v-loading="formLoading"
  6. :model="formData"
  7. :rules="formRules"
  8. label-width="80px"
  9. >
  10. <el-form-item label="属性名称" prop="name">
  11. <el-input v-model="formData.name" placeholder="请输入名称" />
  12. </el-form-item>
  13. </el-form>
  14. <template #footer>
  15. <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
  16. <el-button @click="dialogVisible = false">取 消</el-button>
  17. </template>
  18. </Dialog>
  19. </template>
  20. <script lang="ts" name="ProductPropertyAddForm" setup>
  21. import * as PropertyApi from '@/api/mall/product/property'
  22. const { t } = useI18n() // 国际化
  23. const message = useMessage() // 消息弹窗
  24. const dialogVisible = ref(false) // 弹窗的是否展示
  25. const dialogTitle = ref('添加商品属性') // 弹窗的标题
  26. const formLoading = ref(false) // 表单的加载中:1)修改时的数据加载;2)提交的按钮禁用
  27. const formData = ref({
  28. name: ''
  29. })
  30. const formRules = reactive({
  31. name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
  32. })
  33. const formRef = ref() // 表单 Ref
  34. const attributeList = ref([]) // 商品属性列表
  35. const props = defineProps({
  36. propertyList: {
  37. type: Array,
  38. default: () => {}
  39. }
  40. })
  41. watch(
  42. () => props.propertyList,
  43. (data) => {
  44. if (!data) return
  45. attributeList.value = data
  46. },
  47. {
  48. deep: true,
  49. immediate: true
  50. }
  51. )
  52. /** 打开弹窗 */
  53. const open = async () => {
  54. dialogVisible.value = true
  55. resetForm()
  56. }
  57. defineExpose({ open }) // 提供 open 方法,用于打开弹窗
  58. /** 提交表单 */
  59. const submitForm = async () => {
  60. // 校验表单
  61. if (!formRef) return
  62. const valid = await formRef.value.validate()
  63. if (!valid) return
  64. // 提交请求
  65. formLoading.value = true
  66. try {
  67. const data = formData.value as PropertyApi.PropertyVO
  68. // 检查属性是否已存在,如果有则返回属性和其下属性值
  69. const res = await PropertyApi.getPropertyListAndValue({ name: data.name })
  70. if (res.length === 0) {
  71. const propertyId = await PropertyApi.createProperty(data)
  72. attributeList.value.push({ id: propertyId, ...formData.value, values: [] })
  73. } else {
  74. if (res[0].values === null) {
  75. res[0].values = []
  76. }
  77. attributeList.value.push(res[0]) // 因为只用一个
  78. }
  79. message.success(t('common.createSuccess'))
  80. dialogVisible.value = false
  81. } finally {
  82. formLoading.value = false
  83. }
  84. }
  85. /** 重置表单 */
  86. const resetForm = () => {
  87. formData.value = {
  88. name: ''
  89. }
  90. formRef.value?.resetFields()
  91. }
  92. </script>