项目需求要求用户上传商品的时候可以一次性上传9张图,多余9张提示‘只能上传9张图’,并且每张图右上角有个删除按钮,图片也可以点击放大。
出来的效果图如下:
话不多说,上代码:
<el-form-item label="商品清单/设计图纸:">
<div class="showImg">
<ul>
<li v-for="(item,index) in showImgsrc" :key="index" style="position: relative">
<img :src=item alt="">
<span style=" position: absolute;
top: -5px;
right: -5px;
background: rgb(223, 6, 21);
color: rgb(255, 255, 255);
text-align: center;
line-height: 20px;
font-size: 12px;
width: 20px;
height: 20px;
cursor: pointer;
border-radius: 30px;" @click="clearImg(index)">X</span>
</li>
<li v-if="showImgsrc.length<9">
<div class="uploadImgBtn" id="uploadImgBtn" style="text-align: center">
<span style="display:inline-block;margin:30px auto;font-size: 30px;color: #e5e5e5">
<img src="@/assets/images/addImg.png" alt="">
</span>
<input type="file" @change="uploadImg($event)" class="uploadImg" multiple>
</div>
<span style="font-size: 12px;position: absolute">已上传({{showImgsrc.length}}/9)</span>
</li>
</ul>
</div>
</el-form-item>
方法如下:
uploadImg(e){
let that=this;
let imgFiles=e.target.files;
console.log(e.target.files.length);
if(e.target.files.length+that.showImgsrc.length>=10){
this.showDialog=true;
this.contentText='您最多只能上传9张图片,请重新上传!'
}else{
for( var i = 0 ; i < imgFiles.length ; i++ ){
var fr = new FileReader();
fr.onload = function(e){
that.showImgsrc.push(this.result);
}
fr.readAsDataURL(imgFiles[i]);//读取文件
}
}
}
删除图片:
clearImg(index){
this.showImgsrc.splice(index,1);
},
功能逻辑很简单:就是声明一个空数组showImgSrc,当用户当张图上传的时候,循环图片然后push到showImgSrc空数组里面。最后ul li九宫格显示showImgSrc里的图片。