按照惯例先上效果图:
html:
<form class="form-inline" style="margin-bottom: 2%;">
<div class="form-group has-feedback">
<label style="font-size: 15px;float: left">  商品相册:</label>
<label style="font-size: 15px;float: left">上传图片( {{ imageListLength }} /4)</label>
<div style="width:100%; height:auto; padding-top:-10px; float: left; margin-left: 89px;">
<div style="width:100px; height:100px; position:relative; margin-left:5px; margin-top:10px; float: left; z-index:1" v-for="(img, index) in imageList">
<img :src=img style="width: 100px; height: 100px; border-radius: 10px;">
<a href="#" @click="deleteImg(index)">
<img src="/img/close.png" style="width: 36px; height: 36px; position: absolute; top: -5px; right: -5px; z-index: 100;">
</a>
</div>
<div style="width: 100px; height: 100px; margin-left:5px; margin-top:10px; float:left; position: relative; border-width: 1px; border-color: #9d9d9d; border-style: dashed; display: flex; justify-content: center; align-items: center; border-radius:10px;" @click="inputBtn">
<img src="/img/add.png">
</div>
<input style="display: none" type="file" accept="image/*" name="file" ref="getImageInput" @change="getImageInput">
</div>
</div>
</form>
由于为了方便调试,样式写到了html里面来了,抱歉啦各位…
讲解:
1、它其实是点击加号按钮的div触发被点击,所以这相当于是自己设计自己喜欢的选择文件上传控件。
2、选择文件之后,input的v-model值会发生改变,触发事件@change=“getImageInput”
3、在getImageInput方法中处理file转换成Base64,然后实现回显
4、注意实现完回显之后,记得清空input的v-model值,不然不会触发@change事件
5、图片的右上角设置了X,删除回显图片的样式,所以要记录index,删除指定的索引为index的回显图片
Js:
// 1、
inputBtn() {
vm.$refs.getImageInput.click();
},
// 3、
getImageInput() {
//这里是为了选择图片的时候又取消了选择,导致返回空的情况,需要设置一下,不然会导致错误情况
if (vm.$refs.getImageInput.value != "") {
var inputFile = vm.$refs.getImageInput.files;
if (inputFile.length + vm.imageListLength <= 4) {
vm.submitImageList.push(inputFile[0]);
vm.imageListLength += 1;
var reader = new FileReader();
reader.readAsDataURL(inputFile[0]);
reader.onload = function (event) {
// vm.imageList = event.target.result; 两种写法相同
vm.imageList.push(reader.result);
};
// 4、
vm.$refs.getImageInput.value = "";
} else if (inputFile.length + vm.imageListLength > 4) {
toastr.options = {
timeOut: 1000,
positionClass: "toast-top-center",
};
toastr.error('商品相册最多四张图片');
}
}
},
// 5、
deleteImg(index) {
vm.imageList.splice(index, 1);
vm.submitImageList.splice(index, 1);
vm.imageListLength -= 1
},