昨天在做项目时,有个附件上传的需求,需要使用formdata上传文件,并且支持多文件上传,使用el-upload on-change时发现会调用多次,以下是我整理出来规避的方法。
vue部分:
<el-upload
:on-change="handleUpload"
:on-remove="handleRemove"
:auto-upload="false"
:show-file-list="false"
drag
action="#"
ref="upload"
multiple
style="display:none;"
>
<div class="el-upload__text">拖拽文件或点击上传</div>
</el-upload>
ts/js部分:
// 附件上传
private handleUpload(file, fileList) {
let length = fileList.length;
this.maxFileLength = Math.max(length, this.maxFileLength)
setTimeout(() => {
if (this.maxFileLength !== length) {
return
}
fileList.forEach(item => {
this.fileList.push(item.raw)
})
}, 0)
}
定义一个全局变量maxFileLength 用于计算当前上传次数,如果上传次数等于上传文件的数量长度则将文件放到当前下发文件的参数中。