iview组件库表单中upload组件的校验及upload上传文件个数的限制

1.iview中的upload组件置在form表单中时,自定义校验规则实现.(注重点: 1.给upload组件加上对应的ref用于获取上传文件的fileList; 2.给upload组件双向绑定v-model值,和定义uploadList变量用于表单校验.)

先上效果图:
iview组件库表单中upload组件的校验及upload上传文件个数的限制
iview组件库表单中upload组件的校验及upload上传文件个数的限制

代码部分:


<FormItem label="sim文件:" prop="sim">
          <Upload
            ref="upload"
            v-model="formValidate.sim"
            type="drag"
            :format="['xls','xlsx','csv']"
            :before-upload="handleBeforeUpload"
            :on-format-error='handleErrtype'
            :on-remove='removeFile'
            action="//jsonplaceholder.typicode.com/posts">
            <div style="padding: 20px 0">
                <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                <p>请选择文件或拖拽文件至此完成上传</p>
                <p>(提示:只支持.xls,.xlsx或.csv文件类型)</p>
            </div>
          </Upload>
        </FormItem>
       

       data(){
			 // 自定义验证 判断上传文件 fileList 的长度, 这样就和普通输入框表现一致了
		     const validateUpload = (rule, value, callback) => {
			      if(this.uploadList && this.uploadList.length === 0) {
			        callback(new Error('sim文件必传'))
			      } else {
			        callback()
			      }
		    }
			return {
				uploadList: [],   //上传的文件
				formValidate: {
		        	sim: ""
		     	 },
		     	 ruleValidate: {    
			        sim: [     //upload组件的表单校验规则
			          { required: true, validator: validateUpload, trigger: 'change' }
			        ]
		      	},
			}
		}
       
	
	created(){   
		this.uploadList = this.$refs.upload.fileList   //上传的文件(如果表单是在类似的弹窗子组件内,可写在watch中)
	}
  1. iview中的upload组件的上传文件个数的限制.(因为iview官网文档并没有提供像elm组件库的upoad组件的on-exceed方法,所以只能采用以下这方法处理判断文件个数).
<FormItem label="sim文件:" prop="sim">
          <Upload
            ref="upload"
            v-model="formValidate.sim"
            type="drag"
            :format="['xls','xlsx','csv']"
            :before-upload="handleBeforeUpload"
            :on-format-error='handleErrtype'
            :on-remove='removeFile'
            action="//jsonplaceholder.typicode.com/posts">
            <div style="padding: 20px 0">
                <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                <p>请选择文件或拖拽文件至此完成上传</p>
                <p>(提示:只支持.xls,.xlsx或.csv文件类型)</p>
            </div>
          </Upload>
        </FormItem>

data(){
	return {
		uploadList: [],   //上传的文件
	}
}

methods:{
	handleBeforeUpload (file) {   //上传前钩子
      const check = this.uploadList.length < 1;
      if (!check) {
        this.$Message.error('只允许上传单个文件,请删除已上传文件后再执行上传操作');
      }
      return check;
    },
}

created(){
	this.uploadList = this.$refs.upload.fileList   //上传的文件(如果表单是在类似的弹窗子组件			内,可写在watch中)
}

上一篇:原创-lombok


下一篇:B. Shifting Sort CF1579B