vue 项目antDesign动态表单添加校验

如下图所示
在这里插入图片描述
1,在表单页面中,a-form-model-item 标签可嵌套
2,使用prop传值时使用form表单定义的字段
主要代码如下

 <div  class="form_area" v-for="(item, index) in form.domains" :key="index">
            <a-form-model-item style="display: inline-block;text-align: left;margin: 0px" :prop="'domains.' + index + '.majorName'"
                               :rules="{
                                  required: true,
                                  message: '请输入专业名称',
                                  trigger: 'blur',
                                }">
                <a-select
                        show-search
                        :value="item.majorName"
                        placeholder="专业名称"
                        class="sp-width"
                        :default-active-first-option="false"
                        :show-arrow="false"
                        :filter-option="false"
                        :not-found-content="null"
                        label-in-value
                        @search="handleSearch"
                        @focus="handleFocus(index)"
                        @blur="onBlurSelect"
                        @change="handleChange"
                >
                  <a-select-option v-for="obj in item.majorNameArr" :key="obj.specialtyCode">
                    {{ obj.specialtyName }}
                  </a-select-option>
                </a-select>
            </a-form-model-item>
            <a-form-model-item style="display: inline-block;text-align: center;margin: 0px" :prop="'domains.' + index + '.majorCode'"
                               :rules="{
                                  required: true,
                                  message: '请输入代码',
                                  trigger: 'blur',
                                }">
              <a-input class="m-width" placeholder="专业代码"    v-model="item.majorCode"  @blur="blurInput(item.majorCode)" />
            </a-form-model-item>
            <!--<a-input class="m-width" placeholder="学历" @change="handleXueLiChange"   v-model="item.education" /> -->
            <a-form-model-item style="display: inline-block;text-align: center;margin: 0px" :prop="'domains.' + index + '.education'"
                               :rules="{
                                  required: true,
                                  message: '请选择学历',
                                  trigger: 'change',
                                }">
              <a-select v-model ='item.education' style="width: 90px;margin-left: 16px" >
                <a-select-option v-for="(xuli,index) in xueLiOptions" :key="xuli" >
                  {{xuli}}
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item style="display: inline-block;text-align: center;margin: 0px" :prop="'domains.' + index + '.studentNumber'"
                               :rules="{
                                  required: true,
                                  message: '请输入人数',
                                  trigger: 'blur',
                                }">
              <a-input class="m-width" placeholder="人数"    v-model="item.studentNumber" />
            </a-form-model-item>
<!--            <a-input class="m-width" placeholder="人数"    v-model="item.studentNumber" />-->

            <template v-if="!isDisabled">
              <div style="display: inline-block"  v-if="index === 0" >
                <a-icon class="create_fq_icon m-left" v-if="option =='add'"  @click="addField" type="plus-circle" />
                 <span class="see-code" @click="seeMajorCodeFun">查看专业代码</span>
              </div>
              <a-icon v-else class="create_fq_icon m-left" @click="deleteField(index)" type="minus-circle" />
            </template>

          </div>

全部代码:

<template>
  <div class="add-mem">
    <div class="form-css">
      <a-form-model :model="form"
                    :rules="rules"
                    ref="ruleForm"
                    :wrapper-col="{ span: 10 }"
                    :label-col="{ span: 5 }">
        <a-form-model-item label="院系名称" prop="departmentName">
          <a-input class="form_width" v-model="form.departmentName" />
          <!-- class="form_width" -->
        </a-form-model-item>
        <a-form-model-item label="届别" prop="grade">
          <a-input class="form_width" v-model="form.grade" placeholder="请输入届别,4位年份数字,如2021" />
        </a-form-model-item>
        <a-form-model-item label="专业" style="margin-bottom: 0px " required>
        <!--  <div  class="form_area" v-for="(item, index) in majorArr" :key="index">-->
          <div  class="form_area" v-for="(item, index) in form.domains" :key="index">
            <a-form-model-item style="display: inline-block;text-align: left;margin: 0px" :prop="'domains.' + index + '.majorName'"
                               :rules="{
                                  required: true,
                                  message: '请输入专业名称',
                                  trigger: 'blur',
                                }">
                <a-select
                        show-search
                        :value="item.majorName"
                        placeholder="专业名称"
                        class="sp-width"
                        :default-active-first-option="false"
                        :show-arrow="false"
                        :filter-option="false"
                        :not-found-content="null"
                        label-in-value
                        @search="handleSearch"
                        @focus="handleFocus(index)"
                        @blur="onBlurSelect"
                        @change="handleChange"
                >
                  <a-select-option v-for="obj in item.majorNameArr" :key="obj.specialtyCode">
                    {{ obj.specialtyName }}
                  </a-select-option>
                </a-select>
            </a-form-model-item>
            <a-form-model-item style="display: inline-block;text-align: center;margin: 0px" :prop="'domains.' + index + '.majorCode'"
                               :rules="{
                                  required: true,
                                  message: '请输入代码',
                                  trigger: 'blur',
                                }">
              <a-input class="m-width" placeholder="专业代码"    v-model="item.majorCode"  @blur="blurInput(item.majorCode)" />
            </a-form-model-item>
            <!--<a-input class="m-width" placeholder="学历" @change="handleXueLiChange"   v-model="item.education" /> -->
            <a-form-model-item style="display: inline-block;text-align: center;margin: 0px" :prop="'domains.' + index + '.education'"
                               :rules="{
                                  required: true,
                                  message: '请选择学历',
                                  trigger: 'change',
                                }">
              <a-select v-model ='item.education' style="width: 90px;margin-left: 16px" >
                <a-select-option v-for="(xuli,index) in xueLiOptions" :key="xuli" >
                  {{xuli}}
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item style="display: inline-block;text-align: center;margin: 0px" :prop="'domains.' + index + '.studentNumber'"
                               :rules="{
                                  required: true,
                                  message: '请输入人数',
                                  trigger: 'blur',
                                }">
              <a-input class="m-width" placeholder="人数"    v-model="item.studentNumber" />
            </a-form-model-item>
<!--            <a-input class="m-width" placeholder="人数"    v-model="item.studentNumber" />-->

            <template v-if="!isDisabled">
              <div style="display: inline-block"  v-if="index === 0" >
                <a-icon class="create_fq_icon m-left" v-if="option =='add'"  @click="addField" type="plus-circle" />
                 <span class="see-code" @click="seeMajorCodeFun">查看专业代码</span>
              </div>
              <a-icon v-else class="create_fq_icon m-left" @click="deleteField(index)" type="minus-circle" />
            </template>

          </div>

        </a-form-model-item>
        <a-form-model-item label="联系人">
          <a-input class="form_width" v-model="form.linkMan" />
        </a-form-model-item>
        <a-form-model-item label="联系电话">
          <a-input class="form_width" v-model="form.linkPhone" />
        </a-form-model-item>
        <a-form-model-item label="院系地址">
          <a-input class="form_width" v-model="form.address" />
        </a-form-model-item>
        <a-form-model-item label="备注:">
          <a-input class="form_width self_max"  type="textarea" v-model="form.comment" />
        </a-form-model-item>

        <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }" style="margin-left: 5%">
          <a-button v-if="option=='add'" type="primary" @click="onSubmit">
            提交
          </a-button>
          <a-button v-else type="primary" @click="updateMajorInfo">
            修改
          </a-button>
          <a-button style="margin-left: 10px;" @click="doCancel">
            取消
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
    <a-modal
      v-model="seeMajorFlag"
      class="self-dialog"
      centered
      width="880"
      :bodyStyle="{padding:'0',borderRadius:'0'}"
      :footer="null"
      @ok="() => (seeMajorFlag = false)"
    >
      <three-class-comp
        ref="threeDialog"
        :jobClassList="seeMajorArr"
        :threeMajorList="threeMajorList"
      ></three-class-comp>
      <!--  :form="formMajor"
        @sureMajorMethod="sureMajorMethod" -->
    </a-modal>
  </div>
</template>

<script>

let timeout;
let currentValue;
//
import  { doSearchMajorList ,doAddMajorForm,doGetMajorRow,doUpdateMajorRow,doGetSpecialties} from   '@/http/api.js'
function fetch(value, callback) {
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
  currentValue = value;

  function fake() {
    let param = { name : value}
    doSearchMajorList(param).then(res =>{
      if (currentValue === value) {
        const result = res.data.data || [];
        callback(result);
      }
    })
  }

  timeout = setTimeout(fake, 300);
}
import { mapGetters} from 'vuex'
import ThreeClassComp from "./compontents/ThreeClassComp";
export default {
  name: 'MajorAddPage',
  components: { ThreeClassComp },
  data() {
    let checkGrade = (rule, value, callback) => {
      let structRight = RegExp(/^[0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3}$/).test(value);
      if (!structRight) {
        callback(new Error('请输入正确的届别'));
      } else {
        callback();
      }
    };

    return {
      seeMajorFlag:false,
      isDisabled: false,
      labelCol: {span: 4},
      wrapperCol: {span: 14},
      majorArr: [{majorName: undefined, majorCode: null,education:'',studentNumber:'',majorNameArr:[]}],
      majorNameArr: [],
      majorCodeArr: [],
      value: undefined,
      majorCode:undefined,
      selIndex:'',
      form: {
        address: '',
        comment: '',
        departmentName: '',
        education: '',
        grade: '',
        linkMan: '',
        linkPhone: '',
        majorCode: '',
        majorName: undefined,
        schoolCode: '',
        status: false,
        studentNumber: '',
        domains: [{majorName: undefined, majorCode: null,education:'',studentNumber:'',majorNameArr:[],value:''}],
      },
      majorId:'',
      xueLiOptions:[],
      option:'',
      seeMajorArr: [],
      threeMajorList: [],
      rules: {
        departmentName: [{required: true, message: '请输入院系名称', trigger: 'blur'},
          {max: 30, message: '最多输入30个字符', trigger: 'blur'},
        ],
        grade: [{required: true, message: '请输入届别', trigger: 'blur'},
          { validator: checkGrade, trigger: 'blur' }
        ],
        roles: [{required: true, message: '请输入所属角色', trigger: 'change'}],
      },
    };
  },
  computed:{
    ...mapGetters('login', [
      'userInfo'
    ]),
  },
  created() {
    this.xueLiOptions = this.$store.getters.xueLiOptions

    this.majorId = this.$route.params.id;
    if (this.majorId){ // 修改 edit
      this.option = 'edit'
      this.getMajorDetailById();
    } else { // 新增
      this.option = 'add'
    }
    this.seeMajorList();
  },
  methods: {
    getMajorDetailById () {
      let params = {id:this.majorId}
      doGetMajorRow(params).then(res =>{
        if (res.data.code == 0) {
         // console.log("237==",JSON.parse(JSON.stringify(res.data.major)))
          let cObj = JSON.parse(JSON.stringify(res.data.major))
          // this.form =  JSON.parse(JSON.stringify(res.data.major));
          // this.form.domains = [{majorName: undefined, majorCode: null,education:'',studentNumber:'',majorNameArr:[],value:''}]
          this.form.majorName = cObj.majorName
          this.form.departmentName = cObj.departmentName
          this.form.grade = cObj.grade
          this.form.enable = cObj.enable
          this.form.education = cObj.education
          this.form.facultyId = cObj.facultyId
          this.form.id = cObj.id
          this.form.linkMan = cObj.linkMan
          this.form.linkPhone = cObj.linkPhone
          this.form.majorCode = cObj.majorCode
          this.form.majorName = cObj.majorName
          this.form.studentNumber = cObj.studentNumber
          this.form.domains[0].majorCode = this.form.majorCode
          // this.majorArr[0].majorName = this.form.majorName
          this.form.domains[0].majorName ={key: "", label:  this.form.majorName }
          this.form.domains[0].education = this.form.education
          this.form.domains[0].studentNumber = this.form.studentNumber
        }
      })
    },
    onSubmit() {

      let self = this
      self.$refs.ruleForm.validate(valid => {
        console.log("valid=225=",valid);

        let copyMajorArr = JSON.parse(JSON.stringify(self.form.domains));
        if (copyMajorArr && copyMajorArr.length >0) {
          copyMajorArr.forEach(item =>{
            if (item.majorName){
              item.majorName = item.majorName.label
              item.majorNameArr = []
            }
          })
        }
        if (valid) {
          if (!copyMajorArr[0].majorName){
            this.$message.error("请输入专业信息");
            return
          }
          self.form.schoolCode = self.userInfo.schoolCode
          self.form.majorList = copyMajorArr;
          doAddMajorForm(self.form).then(res =>{
            if (res.data.code == 0){
              if (res.data.list.length == 0){
                self.$message.success('添加院系专业成功!')
                self.$router.push('/majorSet')
              } else{
                let nameStr = ''
                let  hadList = res.data.list[0].majorList
                hadList.forEach(item =>{
                  if(nameStr){
                    nameStr = nameStr + '、' + item.majorName
                  }else{
                    nameStr = item.majorName
                  }
                })
                 self.$message.error(`您添加的院系专业${nameStr}未成功添加`)
                //self.$router.push('/majorSet')
              }

            }
          })
        } else {

        }
      })
    },
    // 修该
    updateMajorInfo(){
      let copyMajorArr = JSON.parse(JSON.stringify(this.form.domains));
      if(copyMajorArr && copyMajorArr.length >0){
        copyMajorArr.forEach(item =>{
          item.majorName = item.majorName.label
        })
      }
      let self = this
      self.$refs.ruleForm.validate(valid => {
        if (valid) {
          self.form.schoolCode = self.userInfo.schoolCode
          self.form.majorList = copyMajorArr;
          self.form.majorName = self.form.majorList[0].majorName
          self.form.majorCode = self.form.majorList[0].majorCode
          self.form.education = self.form.majorList[0].education
          self.form.studentNumber = self.form.majorList[0].studentNumber
          doUpdateMajorRow(self.form).then(res =>{
            if(res.data.code == 0){
              self.$message.success('修改院系专业成功!')
              self.$router.push('/majorSet')
            }
          })
        } else {

        }
      })
    },
    blurInput (val) {
      if (val){
        let structRight = RegExp(/^[a-zA-Z,0-9]{1,7}$/).test(val); // 校验
        console.log("structRight==277==",structRight);
        if (!structRight){
          this.$message.error("专业代码填写不正确!")
        }
      }
    },
    seeMajorCodeFun () {
      this.seeMajorFlag = true;
    },
    doCancel() {
      this.$router.go(-1);
    },
    addField() {
      if (this.form.domains.length<20){
       // this.majorArr.push({majorName: undefined, majorCode: null,education:'',studentNumber:'',majorNameArr:[]})
        this.form.domains.push({majorName: undefined, majorCode: null,education:'',studentNumber:'',majorNameArr:[]})
      }else {
        this.$message.info('最多添加20个专业!')
      }
    },
    deleteField(index) {
      //this.majorArr.splice(index, 1)
      this.form.domains.splice(index, 1)
    },
    handleSearch(value) {
      if (value) {
        // this.majorArr[this.selIndex].inputName = value  // 输入的名称复制给inputName
        this.form.domains[this.selIndex].inputName = value  // 输入的名称复制给inputName
       // fetch(value, data => (this.majorNameArr = data));
        fetch(value, data => (this.form.domains[this.selIndex].majorNameArr = data));
      }
    },
    handleChange(value) {
      // this.value = value;
     // this.form.majorName = value;
      this.form.domains[this.selIndex].majorName = value
      this.form.domains[this.selIndex].majorCode = value.key
      // fetch(value, data => (this.majorNameArr = data));
    },
    onBlurSelect(value) {
      if (this.form.domains[this.selIndex].majorNameArr.length>0) {
      } else {
        if (this.form.domains[this.selIndex].inputName && this.majorArr[this.selIndex].inputName.length >0){
          this.form.domains[this.selIndex].majorName = {key: "", label: this.majorArr[this.selIndex].inputName }
        }
      }
    },
    handleFocus(val){//传的索引值
      this.selIndex = val
    },
    //获取专业列表
    seeMajorList (){
      doGetSpecialties().then((res) => {
        this.seeMajorArr = res.data.data || [];
        // 专业总共有三级,可优化成 内循环
        this.seeMajorArr.forEach((oneObj) => {
          let twoClassList = oneObj.class || [];
          if (twoClassList && twoClassList.length > 0) {
            twoClassList.forEach((twoObj) => {
              twoObj.parentId = oneObj.disciplineCode;
              let threeClassList = twoObj.specialties;
              if (threeClassList && threeClassList.length > 0) {
                threeClassList.forEach((threeObj) => {
                  threeObj.parentId = twoObj.classCode;
                  threeObj.grandFatherId = oneObj.disciplineCode;
                  this.threeMajorList.push(threeObj);
                });
              }
            });
          }
        });
      });
    }
  },

}
</script>

<style scoped lang="less">
.add-mem{
  background-color: #FFFFFF;
  /*width: 1136px;*/
  min-height: 630px;
  padding-top: 30px;
  padding-bottom: 50px;
  .form-css{
    .form_width {
      width: 514px;
      &.field {
        width: 217px;
      }
    }
    .self_max{
      max-width: none;
    }
    .sp-width{
      width: 200px;
    }
    .m-width{
      width: 88px;
      margin-left: 16px;
    }
    .see-code{
      color: rgba(0, 0, 0, 0.45);
      font-size: 14px;
      margin-left: 20px;
      cursor: pointer;
      &:hover{
        color: #437FFF;
      }
    }
    .form_area{
      width: 668px;
      height: 60px;
      /*margin-bottom: 16px;*/
      /*border: 1px solid red;*/
      .m-left{
        margin-left: 16px;
      }
    }
    .create_fq_icon {
      font-size: 18px;
      vertical-align: middle;
      color: #437FFF;
    }
  .from-index{
    display: inline-block;
    margin-right: 10px;
  }
  }
}

</style>
<style>
  /*.self-dialog .ant-modal-content {
    border-radius: 2px;
  }*/
</style>

Logo

前往低代码交流专区

更多推荐