说明
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();
}
},