最近作公司某某活动,里面有个图片预览上传的功能。为了KPI分享文章原创的40%,匆忙动手写下,欢迎各类吐槽。app
1.先上图 ui
弄个框框预览图片,弄个框框添加图片this
<div class="page">
<div class="upload-img">
<!-- 上传图片 -->
<div class="upload-img__content">
<div class="upload-img__item" v-for="(item,index) in imgList" :key="index">
<img :src="item" alt="用户上传的附件"/>
</div>
<div class="upload-img__item">
<div class="upload-img__add"></div>
<input class="file" type="file" name="file" accept="image/*" v-on:change="changeImage($event)" ref="fileInput" multiple>
</div>
</div>
<!-- 上传图片 -->
</div>
</div>
</template>
复制代码
3.重点来了,预览图片spa
changeImage(e) {
var vm = this;
var array = e.target.files;
if(array.length + vm.imgList.length < 10){ //不超过9张
for (let index = 0; index < array.length; index++) {
var file = array[index];
if (file.size / 1024 / 1024 > 2) {
this.$Message.info("图片不能超过2M");
return;
}
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e) {
console.log(e)
//预览
vm.imgList.push(this.result);
};
}
}else{
alert('您还能选X张图片');
}
},
//下一步
addInquireNext(){
//上传图片
let vm = this;
if (vm.$refs.fileInput.files.length !== 0) {
var image = new FormData();
image.append("file", vm.$refs.fileInput.files[0]);//此处待接口传值
// inquire.upLoadMoreImg.r(image).then(res => {});
}
}
复制代码
当当当,完成了!!! 请欣赏效果以下图。code