Ant design Vue 实现动态表单及验证

<template>
<a-form-model
      ref="dynamicValidateForm"
      :model="dynamicValidateForm"
      v-bind="formItemLayoutWithOutLabel"
    >
      <div v-for="(domain, index) in dynamicValidateForm.domains" :key="domain.key">
        <a-form-model-item
          :prop="'domains.' + index + '.info'"
          :rules="{
            required: true,
            message: '状态说明不能为空',
            trigger: 'blur',
          }"
          :style="{width: '30%', 'margin-right': '20px', 'display': 'inline-block'}"
        >
          <a-input
            v-model="domain.info"
            placeholder="请输入状态说明"
          />
        </a-form-model-item>
        <a-form-model-item
          :prop="'domains.' + index + '.val'"
          :rules="{
            required: true,
            message: '状态说明参数值不能为空',
            trigger: 'blur',
          }"
          :style="{width: '30%', 'margin-right': '20px', 'display': 'inline-block'}"
        >
          <a-input-number
            v-model="domain.val"
            :min="0"
            :max="9999999999"
          />
        </a-form-model-item>
        <span
          v-if="dynamicValidateForm.domains.length > 1"
          class="dynamic-delete-button"
          :disabled="dynamicValidateForm.domains.length === 1"
          @click="removeDomain(domain)"
        >
          <i class="iconfont icon-stop" />
        </span>
      </div>
      <a-row v-if="isError" :gutter="24">
        <a-col :span="22" :offset="2" class="red">{{ tips }}</a-col>
      </a-row>
    </a-form-model>
</template>
<script>
export default {
  name: 'Test',
  data() {
    return {
      formData: {
        key: null,
        unit: undefined,
        name: undefined,
        statusList: [{
          key: 0,
          info: '',
          val: ''
        }]
      },
      labelCol: { span: 5 },
      wrapperCol: { span: 17 },
      dynamicValidateForm: {domains: []}
    }
  },
  methods: {
    removeDomain(item) {
      let index = this.dynamicValidateForm.domains.indexOf(item)
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1)
      }
    },
    addDomain() {
      this.dynamicValidateForm.domains.push({
        info: '',
        val: '',
        key: Date.now()
      })
      this.isError = false
    }
    }
}
</script>

Tips: 动态表单不能被a-row包裹,a-form-model上不要写rule,写在a-form-model-item上


评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注