当前位置:   article > 正文

vue3.0 element-ui中el-upload的before-upload方法返回false时submit()不生效解决方法_element-plus before-upload 返回false 列表不显示

element-plus before-upload 返回false 列表不显示

需求:手动上传图片,非JPG、PNG格式无法选择

       <el-upload
	       action="https://jsonplaceholder.typicode.com/posts/"
	               list-type="picture-card"
	               :auto-upload="false"
	               ref='uploadPhoto'
	               :multiple="false"
	               :on-preview="handlePictureCardPreview"
	               :before-upload="beforeUploadImg"
	               :on-change="changeUploadImg"
	               :on-remove="handleRemove"
	               @clearFiles="clearFilesPhoto"
	               accept="image/jpeg,image/png">
	           <i class="el-icon-plus"></i>
	
      </el-upload>
      <el-button @click="cancelUploadPhoto">取 消</el-button>
      <el-button type="primary" @click="submitUpload">发送</el-button>
                                          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

问题,由于设置了 :auto-upload="false"手动上传,导致 :before-upload="beforeUploadImg"不生效,若使用beforeUpload验证,虽然能阻止上传,但图片框依然留下空白图片,使用on-remove清除列表的话,显然有些繁琐多余。

快速解决办法::on-change="changeUploadImg"代替:before-upload,使用element源码中的handleRemove函数清除文件,并阻止选中。

 //文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
      changeUploadImg(file) {
        console.log(file);
        //保存消息图片
        // this.messageImgPost = file.raw;
        const isJPG = file.raw.type === 'image/jpeg';
        const isPNG = file.raw.type === 'image/png';
        // const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG && !isPNG) {
          this.$message.error('上传图片只能是 JPG 或者 PNG 格式!');
          //执行清空图片
          // this.$refs.uploadPhoto.clearFiles();
         // 取消时在文件列表中删除该文件
          this.$refs.uploadPhoto.handleRemove(file);
          return (isJPG || isPNG);

        } else {
          this.newArrayImg.push(file.raw);
          this.messageImgPost = this.newArrayImg;
        }
      },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

注意:这里使用了 this.$refs.uploadPhoto.handleRemove(file);清空非JPG、PNG文件

效果:

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/805639
推荐阅读