antd的upload上传组件,上传成功后清除表单校验——基础积累

今天在写后台管理系统时,发现之前的一个bug,就是antdupload上传组件,需要进行表单校验。

在这里插入图片描述
直接上代码:

1.html部分

 <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      :rules="rules"
    >
    xxxxxxxxx
      <a-form-model-item label="导入" prop="fileList" ref="upload">
        <a-upload
          name="file"
          :multiple="true"
          action="xxxxx/template-data"
          accept=".xlsx"
          :customRequest="customRequest"
          :fileList="form.fileList"
          :remove="handleRemove"
        >
          <a-button type="primary">
            <a-icon type="cloud-upload" /> 导入
          </a-button>
        </a-upload>
      </a-form-model-item>
      xxxxxxx
</a-form-model>

2.js部分

export default{
    
    
	data(){
    
    
		return{
    
    
			form:{
    
    },
			formData:null,
			rules: {
    
    
		        quoteSupplierCode: [
		          {
    
     required: true, message: '请选择供应商', trigger: 'change' },
		        ],
		        fileList: [
		          {
    
     required: true, message: '请上传文件', trigger: 'change' },
		        ],
		      },
		}
	}
}

2.1 上传成功的方法——customRequest

customRequest(files) {
    
    
  let file = files.file;
  this.form.fileList = [file];
  this.$forceUpdate();
  this.formData = new FormData();
  this.formData.append('StreamContent', file);
  //this.$refs.ruleForm.clearValidate('fileList'); //清除图片校验文字——这个方法不生效
  delete this.rules['fileList'];
},

this.$refs.ruleForm.clearValidate(‘fileList’); //清除图片校验文字——这个方法不生效
delete this.rules[‘fileList’]; 这个是生效的,而且页面上 导入 字段左边还是有必填校验的,只是不会走校验而已

2.2 移除文件的方法——handleRemove

handleRemove() {
    
    
  this.form.fileList = [];
  this.formData = null;
  this.$forceUpdate();
  this.rules['fileList'] = {
    
    
    required: true,
    message: '请上传文件',
    trigger: 'change',
  };
},

2.3 表单校验方法——handleOk

handleOk() {
    
    
  const form = this.$refs.ruleForm;
  form.validate((valid) => {
    
    
    if (valid) {
    
    
		xxxxxx
	}
  })
}

3.注意:该页面/弹窗打开的时候,需要添加下面的代码,否则就直接没有文件导入的校验了!!!

我这边是弹窗,所以是在showModal方法里面写的:

showModal(ids) {
    
    
  this.visible = true;
  this.form = {
    
     ids: ids, isDelete: true, deliveryDays: 5 };
  this.$nextTick(() => {
    
    
    this.$refs.ruleForm.clearValidate();
    this.rules['fileList'] = {
    
    
      required: true,
      message: '请上传文件',
      trigger: 'change',
    };
  });
},

总结:使用clearValidate(['指定Prop'])或者clearValidate('指定Prop')是不生效的,然后我使用的方法就是上传文件成功后,将rules中的文件prop删除,也就是delete obj['指定prop'],然后在删除文件或者该页面第一次打开时,给rules添加指定prop的校验规则。

使用clearValidate(['指定Prop'])或者clearValidate('指定Prop')是不生效的,然后我使用的方法就是上传文件成功后,将rules中的文件prop删除,也就是delete obj['指定prop'],然后在删除文件或者该页面第一次打开时,给rules添加指定prop的校验规则

猜你喜欢

转载自blog.csdn.net/yehaocheng520/article/details/133708971