vue el-upload 上传图片列表校验不通过后多删除了一张图片

问题

最近在使用 element-uiel-upload 组件上传图片列表时,发现当上传的图片校验不通过时,会将上一张已经上传成功的图片删除了。

场景

已经上传了一张图片1,再上传另一张图片2,如果当前这张图片2校验不通过,会提示失败并且删除当前图片2,同时,也会将上一张已经上传成功的图片1也删除。

组件主要代码:

<el-upload multiple ref="upload"
 :action="url" :file-list="fileList"
 :before-upload="beforeAvatarUpload"
 :on-success="handleSuccess"
 :on-remove="handleRemove"
 accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG,.GIF">
     <el-button>
         <i class="el-icon-document" />上传
     </el-button>
     <span slot="tip" class="el-upload__tip">
         支持上传图片,单文件上传大小限制10MB,最多上传10张附件
      </span>
</el-upload>

-----------------------------------------------------------------------
// 上传前校验,只写了简单几个条件
beforeFileUpload (file) {
   
   const isLenLimit = this.fileList.length < 20;
   const isLtSize = file.size / 1024 / 1024 < this.limitSize;
   if (!isLenLimit) {
   
      this.$message.error('最多只能上传20个附件');
   }
   if (!isLtSize) {
   
      this.$message.error(`上传图片大小不能超过${
     this.limitSize}MB!`)
   }
   return isLenLimit && isLt10M;
},
// 附件删除
handleRemove (file, fileList) {
   
    this.findItem(file.uid)
    this.fileList.splice(this.picIndex, 1)
    fileList = JSON.parse(JSON.stringify(this.fileList))
    this.exportImg(fileList)
},

原因分析

beforeUpload 事件中,添加用户上传文件的判断操作,该事件在返回 false 时,会自动终止上传事件。
但是!!!当上传失败后,element-ui el-upload 组件会自动执行 on-remove 事件。
根据 handleRemove 方法,file 是上传失败的文件的信息,此时 this.fileList(保存上传成功的文件)中并没有保存这个文件,findItem 会返回 -1,splice(-1,1) 会删除 this.fileList 数组中的最后一个数据项。

解决方案

on-remove 事件中添加判断,执行删除操作时,区分已上传的图片和出错的图片,确认文件是否需要被删除。如下:

handleRemove (file, fileList) {
    // 删除图片
      if (file && file.status === 'success') {
   
        this.findItem(file.uid)
        this.fileList.splice(this.picIndex, 1)
        fileList = JSON.parse(JSON.stringify(this.fileList))
        this.exportImg(fileList)
      }
}

页面效果:

完整版代码:

<template>
  <div class="img-upload-container">
    <div class="img-upload" :class="{
    'limit-num': fileList.length>=limit, 'mini': size === 'small'}">
      <el-upload ref="upload" :action="url" :file-list="fileList" list-type="picture-card" :on-success="handleSuccess" :on-remove="handleRemove" :on-preview="handlePictureCardPreview" :before-upload="beforeAvatarUpload">
        <i class="el-icon-plus">i>
        <p class="el-upload__tip" slot="tip" v-if="tips">{
  {tips}}p>
        <div slot="file" slot-scope="{file}" class="img-con">
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" crossorigin>
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
              <i class="el-icon-zoom-in">i>
            span>
            <span class="el-upload-list__item-delete" @click="handleRemove(file)">
              <i class="el-icon-delete">i>
            span>
            <span v-if="size === 'small

你可能感兴趣的:(#,Vue,2.x,vue.js,javascript,前端)