form-items.vue 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <template>
  2. <el-form
  3. ref="formRef"
  4. :model="dynamicValidateForm"
  5. label-width="120px"
  6. class="demo-dynamic"
  7. >
  8. <el-form-item
  9. prop="email"
  10. label="Email"
  11. :rules="[
  12. {
  13. required: true,
  14. message: 'Please input email address',
  15. trigger: 'blur',
  16. },
  17. {
  18. type: 'email',
  19. message: 'Please input correct email address',
  20. trigger: ['blur', 'change'],
  21. },
  22. ]"
  23. >
  24. <el-input v-model="dynamicValidateForm.email" />
  25. </el-form-item>
  26. <el-form-item
  27. v-for="(domain, index) in dynamicValidateForm.domains"
  28. :key="domain.key"
  29. :label="'Domain' + index"
  30. :prop="'domains.' + index + '.value'"
  31. :rules="{
  32. required: true,
  33. message: 'domain can not be null',
  34. trigger: 'blur',
  35. }"
  36. >
  37. <el-input v-model="domain.value" />
  38. <el-button class="mt-2" @click.prevent="removeDomain(domain)"
  39. >Delete</el-button
  40. >
  41. </el-form-item>
  42. <el-form-item>
  43. <el-button type="primary" @click="submitForm(formRef)">Submit</el-button>
  44. <el-button @click="addDomain">New domain</el-button>
  45. <el-button @click="resetForm(formRef)">Reset</el-button>
  46. </el-form-item>
  47. </el-form>
  48. </template>
  49. <script lang="ts" setup>
  50. import { reactive, ref } from 'vue'
  51. import type { FormInstance } from 'element-plus'
  52. const formRef = ref<FormInstance>()
  53. const dynamicValidateForm = reactive<{
  54. domains: DomainItem[]
  55. email: string
  56. }>({
  57. domains: [
  58. {
  59. key: 1,
  60. value: '',
  61. },
  62. ],
  63. email: '',
  64. })
  65. interface DomainItem {
  66. key: number
  67. value: string
  68. }
  69. const removeDomain = (item: DomainItem) => {
  70. const index = dynamicValidateForm.domains.indexOf(item)
  71. if (index !== -1) {
  72. dynamicValidateForm.domains.splice(index, 1)
  73. }
  74. }
  75. const addDomain = () => {
  76. dynamicValidateForm.domains.push({
  77. key: Date.now(),
  78. value: '',
  79. })
  80. }
  81. const submitForm = (formEl: FormInstance | undefined) => {
  82. if (!formEl) return
  83. formEl.validate((valid) => {
  84. if (valid) {
  85. console.log('submit!')
  86. } else {
  87. console.log('error submit!')
  88. return false
  89. }
  90. })
  91. }
  92. const resetForm = (formEl: FormInstance | undefined) => {
  93. if (!formEl) return
  94. formEl.resetFields()
  95. }
  96. </script>