項目需求要求用戶上傳商品的時候能夠一次性上傳9張圖,多餘9張提示‘只能上傳9張圖’,而且每張圖右上角有個刪除按鈕,圖片也能夠點擊放大。數組
出來的效果圖以下:this
話很少說,上代碼:spa
1 <el-form-item label="商品清單/設計圖紙:"> 2 <div class="showImg"> 3 <ul> 4 <li v-for="(item,index) in showImgsrc" :key="index" style="position: relative"> 5 <img :src=item alt=""> 6 <span style=" position: absolute; 7 top: -5px; 8 right: -5px; 9 background: rgb(223, 6, 21); 10 color: rgb(255, 255, 255); 11 text-align: center; 12 line-height: 20px; 13 font-size: 12px; 14 width: 20px; 15 height: 20px; 16 cursor: pointer; 17 border-radius: 30px;" @click="clearImg(index)">X</span> 18 </li> 19 <li v-if="showImgsrc.length<9"> 20 <div class="uploadImgBtn" id="uploadImgBtn" style="text-align: center"> 21 <span style="display:inline-block;margin:30px auto;font-size: 30px;color: #e5e5e5"> 22 <img src="@/assets/images/addImg.png" alt=""> 23 </span> 24 <input type="file" @change="uploadImg($event)" class="uploadImg" multiple> 25 </div> 26 <span style="font-size: 12px;position: absolute">已上傳({{showImgsrc.length}}/9)</span> 27 </li> 28 </ul> 29 </div> 30 </el-form-item>
方法以下:設計
1 uploadImg(e){ 2 let that=this; 3 let imgFiles=e.target.files; 4 console.log(e.target.files.length); 5 if(e.target.files.length+that.showImgsrc.length>=10){ 6 this.showDialog=true; 7 this.contentText='您最多隻能上傳9張圖片,請從新上傳!' 8 }else{ 9 for( var i = 0 ; i < imgFiles.length ; i++ ){ 10 var fr = new FileReader(); 11 fr.onload = function(e){ 12 that.showImgsrc.push(this.result); 13 } 14 fr.readAsDataURL(imgFiles[i]);//讀取文件 15 } 16 } 17 }
刪除圖片:code
1 clearImg(index){ 2 this.showImgsrc.splice(index,1); 3 },
功能邏輯很簡單:就是聲明一個空數組showImgSrc,當用戶當張圖上傳的時候,循環圖片而後push到showImgSrc空數組裏面。最後ul li九宮格顯示showImgSrc裏的圖片。orm