vue中使用element-ui 的upload组件,before-upload验证不通过后为什么会触发了on-remove的执行?

442 阅读1分钟
1、html结构
  <el-upload
    :action="uploadPicAction"
    :headers="{'token': token }"
    :before-upload="beforeExcelUpload"
    :on-success="onUploadSuccessPicture"
    :on-remove="handleRemovePic"
    :on-exceed="handleExceed"
    list-type="picture-card"
    :file-list="picList"
    :limit="9"
    multiple
    accept=".jpg,.png,.gif,.jpeg,.psd"
  >
    <i class="el-icon-plus" />
  </el-upload>

2、js代码

methods: {

  // 上传文件之前的钩子
  beforeExcelUpload(file) {
    let fileReg = ''
    let errMsg = ''
    const picReg = /\.(jpg|png|gif|jpeg|psd)$/
    const attachmentReg = /\.(doc|docx|ppt|pptx|xls|xlsx)$/
    const picErrorMsg = '只能上传图片格式,如:|.jpg |.png |.gif |.jpeg |.psd格式!'
    const attachmentErrorMsg = '只能上传文档格式格式,如:|.doc |.docx |.ppt |.xls |.xlsx格式!'

    fileReg = this.uploadType === 1 ? attachmentReg : picReg
    errMsg = this.uploadType === 1 ? attachmentErrorMsg : picErrorMsg

    let limitMax = 0
    const limitErrMsg = this.uploadType === 1 ? '200M' : '400KB'
    const limitMin = (file.size / 1024 / 1024) > 0
    const limitFileMax = (file.size / 1024 / 1024) < 200 // 附件不能大于200MB
    const limitPictureMax = (file.size / 1024 / 1024) < (400 / 1024) // 图片不能大于400kb

    limitMax = this.uploadType === 1 ? limitFileMax : limitPictureMax

    if (!fileReg.test(file.name)) {
      this.$message.error(errMsg)
    }
    if (!limitMin) {
      this.$message.error('上传的文件不能为空!')
    } else if (!limitMax) {
      this.$message.error(`上传的文件大小不能超过 ${limitErrMsg}!`)
    }
    return fileReg.test(file.name) && limitMin && limitMax
  },
  // 附件上传成功后
  onUploadSuccessAttachments(res) {
    console.log('上传成功', res, this.fileList)
    if (res.status === 200) {
      this.ruleForm.attachList.push({
        filename: res.data.filename,
        path: res.data.path
      })
    }
  },
  // 图片上传成功后
  onUploadSuccessPicture(res, file, fileList) {
    if (res.status === 200) {
      this.ruleForm.pictureList.push({
        filename: res.data.name,
        path: res.data.path
      })
    }
  },
  
  // 删除图片
  handleRemovePic(file, fileList) {
    if (file && file.status === 'success') {
      const index = this.ruleForm.pictureList.findIndex(item => item.filename === file.name)
      this.ruleForm.pictureList.splice(index, 1)
    }
  },
  // 上传超出数量钩子函数
  handleExceed(files, fileList) {
    let msg = ''

    msg = this.uploadType === 1 ? '最多只能上传9个文件!' : '最多只能上传9张图片!'
    this.$message.warning(msg)
  }
  
}