// html <div class="preview" v-show="previewImg" @click="previewImg=''"><img :src="previewImg" alt="" /></div> <div class="uploadBox2"> <div class="uploadBtn uploadImg" v-for="(item,index) in imgDatas"> <span class="close" @click="deleteImg(index)">✕</span> <img :src="item" alt="" @click="previewImg=item"> </div> <div class="uploadBtn"> <span class="iconadd">+</span> <input type="file" accept="image/*" multiple @change="changeImage($event)"/> </div> </div>
// css .uploadBox2{ display: flex; display: -webkit-flex; flex-wrap: wrap; -webkit-flex-wrap: wrap; } .uploadBtn{ width: 60px; height: 60px; border: 1px dashed #E6E6E6; position: relative; margin: 0 8px 15px 0; } .uploadImg{ border: none; } .uploadBtn img{ width: 100%; height: 100%; } .uploadBtn input{ width: 100%; height: 100%; opacity: 0; } .close{ width: 15px; height: 15px; line-height: 15px; text-align: center; position: absolute; top: -6px; right: -6px; color: #fff; background: rgba(0,0,0,0.6); border-radius: 50%; font-size: 10px; } .iconadd{ font-size: 20px; color: #E6E6E6; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); z-index: 0; } .preview{ position: fixed; top: 0; left: 0; bottom: 0; right: 0; z-index: 99; background: rgba(0,0,0,0.9); } .preview img{ width: 100%; height: 100%; object-fit: contain; vertical-align: middle; }
// JS data(){ return(){ filesArr: [], imgDatas: [], previewImg: '', // 放大预览图片 } }, methods: { // 上传图片 changeImage(e){ let files = e.target.files; // 如果没有选中文件,直接返回 if (files.length === 0) { return; } let reader; let file; let imgDatas = this.imgDatas; for (let i = 0; i < files.length; i++) { file = files[i]; this.filesArr.push(file); reader = new FileReader(); if (/.(jpe?g|png|gif)$/i.test(file.name)) { reader.onload = function(e) { if (imgDatas.indexOf(this.result) === -1) { // 判断数组里值相同的无法上传,具体看自己需求 imgDatas.push(this.result); } }; reader.readAsDataURL(file); } } e.target.value = ''// 清空value值防止 同一张图片无法重复提交 }, // 删除图片 deleteImg(index){ this.filesArr.splice(index,1); this.imgDatas.splice(index,1); console.log(this.filesArr); console.log(this.imgDatas); }, }
最后实现的效果:
(预览放大图片:)