【VUE的Form表单】在Form表单中对上传附件a-upload组件配置必填校验

背景

在做form表单的时候,会碰到前端要对表单进行校验处理,通过会是有input输入框或者select下拉框等,针对这些普通的表单项可以直接直接参照官网上的表单校验方式去处理:prop和v-model属性搭配去进行设置,或者直接在formModel上配置一个ref属性,然后最后提交表单时利用:this.$refs.formValidate.validate((val)=>{ // 这里的val是个布尔值,如果校验通过返回true,否则返回false。})去进行整体的校验即可。
但是由于a-upload有一些特殊性,相信使用过这个组件,发现他无法正常校验的人应该清楚,我也细说不清楚,反正解决方案指直接放下边了,直接CV吧。

解决方案:

1、表单部分代码

  <!-- 表单a-form-model整体绑定的是 mdl对象:model="mdl" -->
  <a-form-model ref="form" :model="mdl">
    <a-row>
      <!-- 正常校验:prop 和 v-model 搭配设置校验 -->
      <!-- 举例 :输入框  -->
      <a-col :span="12">
        <a-form-model-item
          label="正常校验"
          prop="input"
          :rules="{
    
    
            required: true,
            message: '请输入',
            trigger: ['blur', 'change'],
          }"
        >
          <a-input
            placeholder="请输入"
            v-model="mdl.input"
            :maxLength="50"
          />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <!-- 上传附件 a-upload -->
      <a-col :span="12">
        <a-form-model-item
          label="上传附件"
          prop="files"
          :rules="{
    
    
            required: true,
            validator: this.uploadFileChange,
            trigger: ['change'],
          }"
        >
        // 这里 change 和 remove 就正常写就行,只要是对 fileList 去进行变更处理
        // 然后去触发对 fileList 的监听,变更 mdl.fileList 属性值
          <a-upload
            name="files"
            :multiple="true"
            :headers="headers"
            action="/api/上传接口/upload"
            :file-list="fileList"
            :before-upload="beforeUpload"
            @change="fileListChange"
            :remove="removeFile"
          >
            <a-button>
              <a-icon type="upload" /> 点击上传文件
            </a-button></a-upload
          >
        </a-form-model-item>
      </a-col>
    </a-row>
  </a-form-model>

2、js部分代码

// 自定义上传附件校验
uploadFileChange(rule, value, callback) {
    
    
  if (this.fileList.length === 0) {
    
    
    return callback('请选择需要上传的文件')
  } else {
    
    
    return true
  }
},
// vue 添加一个监听
watch: {
    
    
  fileList: {
    
    
    handler: function (val, oldVal) {
    
    
      if (val.length == 0) {
    
    
        // null 来触发校验
        this.mdl.fileList = null
      } else {
    
    
        this.mdl.fileList = JSON.stringify(val)
      }
    },
  },
},

这里最后表单提交时对表单整体进行校验也是生效的:

save(){
    
    
 this_.$refs.form.validate((res, object) => {
    
    
 	 // 注意:这个object参数也可以去看表单内哪个校验未通过
     if (!res) {
    
    
          this_.$message.error('请根据提示信息补全提交的内容信息')
          return
     } else {
    
    
          //调取保存接口 正常保存数据即可
          ...
     }
  })
}

页面效果就是:

1、不填数据点击提交,对表单整体进行校验

在这里插入图片描述

2、整体空数据触发校验之后,上传文件,提示消失

在这里插入图片描述

3、全数据之后,再次点击提交,校验通过正常提交

在这里插入图片描述

最后:

对于a-upload其他的一些配置,大家可以看我的另一篇文章:vue限制a-upload组件上传文件大小、格式、数量 以及 像素

然后,再见!欢迎各位点赞 + 收藏 + 评论区留言!!!

猜你喜欢

转载自blog.csdn.net/weixin_55846296/article/details/126991082