form-items.vue 2.5 KB

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