http-request=“httpRequest“,自定义上传导致的el-upolad上传图片n次问题,解决想了很久

一般的后台管理系统都是在el-dialog 里加el-upload标签,我做的功能是图片先缓存在页面,等带提交的时候在把图片添加到后台代码如下:

<el-upload
              class="avatar-uploader"
              ref="upload"
              action="string"
              :show-file-list="false"
              :http-request="httpRequest"
              :before-upload="beforeUpload"
              :on-change="filechange"
              :auto-upload="false"
              >
              <img v-if="form.logo" :src="form.logo" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>

点击添加触发:on-change

filechange(file, fileList) {
      // 如果没有选取文件,可以加个字段来控制流程
      this.localFile=file.raw  // 或者 this.localFile=file.raw
      this.upload_flag = true;
      /*if(fileList.length===2){
        fileList.splice(0,1);
      }
      else*/
      if (this.localFile.type.indexOf("image/") == -1) {
        this.msgError("文件格式错误,请上传图片类型,如:JPG,PNG后缀的文件。");
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(this.localFile);
        reader.onload = () => {
          this.form.logo = reader.result;
        };
      }
    },

注意了开始埋雷了。然后调用this.$refs.upload.submit();触发http-request=“httpRequest“

httpRequest(param) { // param是自带参数。 this.$refs.upload.submit() 会自动调用httpRequest方法.在里面取得file
      this.$refs['form'].validate((valid) => {
        if (valid) {
          console.log(param)
          var fileObj = param.file; // 相当于input里取得的files
          let formData = new FormData();
          formData.append("logofile",fileObj);
          /*this.form.logo='';*/
          uploadLogo(formData).then(response => {
            this.form.logo = process.env.VUE_APP_BASE_API + response.imgUrl;
            param = null;
          });
          console.log(this.form)
        }
      })
    }

点击提交(增改界面类似),图片成功到后台,返回主页面表格, 图片成功添加,你以为完事大吉了吗?

你在继续添加图片,你会发现,后台添了两张图片,明明只添了一张,为什么变两张。。。(两张图片分别为之前添的第一张图片和这次添的图片)
注意了,解密开始,再filechange(file, fileList) 里加个console.log( fileList.length) 你第二次添加图片你会发现length 为2,第一次为1.
证明缓存里有两个file;
当你第二次添加调用this.$refs.upload.submit() ,你会发现连续执行了两个httpRequest(param) 神不神,前一个el-dialog都关闭了,缓存的param还在祸害第n次添加或者修改。聪明的你看到这里肯定想到怎么解决了。

解决办法!!!

  1. this.$router.go(0);直接刷新
  2. 在<el-dialog 里添加 :destroy-on-close=“true”,意思是关闭清空缓存>
  3. 完美解决。本人第一次写博客,觉得稍微有点用可不可以给一个小小的赞好吗,转载请千万标明出处。刚毕业在深圳月薪才3000,真的不想干了,为解决问题的快乐,干杯。。。有没有跟我一样的,抱抱。加油

本文地址:https://blog.csdn.net/weixin_44102328/article/details/109391441