ElememtUI 多图上传

  1. 说明

multiple 是否支持多选 ,

limit 限制上传图片数量 搭配on-exceed 文件超出个数限制时的钩子 使用

on-success 文件上传成功时的钩子 function(response, file, fileList) fileList :已上传成功的文件列表 用于处理一次性选择多张图片时判断清空已上传文件列表

<div style="color:#FF4500;">
    2M以内的JPG或PNG的图片,最多10张
</div>
<div class="upload-img--wrap">
    <div
    class="img-box"
    v-for="(item, idx) in fileUrls"
    :key="item"
    >
        <img class="img" :src="uploadUrl+ item" />
        <i class="el-icon-delete" v-if="!isDetail" @click="handleRemove(idx)"></i>
    </div>
    <el-upload :headers="headers" v-if="fileUrls.length<10" :show-file-list="false" list-type="picture-card" ref="imgUpload"
     :action="uploadUrl" :on-success="handleSuccess"  :on-error="handleError"
    class="avatar-uploader" :before-upload="beforeAvatarUpload" :on-exceed="handleExceed"  :limit="10- fileUrls.length" multiple >
        <i  class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
</div>  

注: 当上传失败时 err 抓取到的数据如上展示,故我们需要在进行转换处理移除掉前面的Error

handleError(err){
    let myError=err.toString();//转字符串
    myError=myError.replace("Error: ","")//去掉前面的
    myError=JSON.parse(myError);//转对象
    this.$refs.imgUpload.clearFiles();
    this.$notify.error(myError.msg || "上传失败");
},
handleRemove(index){
    this.fileUrls.splice(index, 1);
},
// 文件超出限制
handleExceed(files, fileList) {
    this.$notify.error("最多上传10张照片");
    // 清空已上传的文件列表,不然数量限制会有问题
    this.$refs.imgUpload.clearFiles();
},
beforeAvatarUpload(file,fileList) {        
    const isJPG = file.type === "image/jpg" || file.type === "image/png";
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M || !isJPG || !file.type) {
        this.$message({
        showClose: true,
        message: "图片需为JPG或PNG格式,大小不超过2M",
        type: "error"
        });
        return false;
    }
    this.headers["Authorization"] = "Bearer "+store.getters.access_token
    return isJPG && isLt2M;
},

贴出ElementUI 源码

由上可以看出on-exceed 文件超出限制钩子函数的触发条件是 已上传文件列表 加上当前选择图片选择列

handleSuccess(res, file,fileList){
    if(res.code == 0){
        this.fileUrls.push(res.data);
        if(fileList && fileList.length>1){//处理一次性选择多张图片上传,清空上传成功的文件列表
            this.preImgLength ++ ;
            if(this.preImgLength == fileList.length){
                this.$refs.imgUpload.clearFiles();
            }
        }else{
            this.$refs.imgUpload.clearFiles();
        }
    }else{
        this.$notify.error(res.msg || "上传失败");
        this.$refs.imgUpload.clearFiles();    
    }  
},

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值