所遇到的问题?此组件的开发是为了后台管理的多图上传,并实现本地预览修改,当用户确认后开始整体提交,此组件使用了我的另一篇文章所用到的组件
选择多个文件后无法实现本地预览?
使用es6的for of 对获取到的文件对象数组 filelist进行迭代循环
使用 FileReader 对象将选择的图片文件转换成可以前端展示的 base 64数据
在新数组被将图片数据push进去就可以实现本地多图预览了
fileChange(files) { // files 为接收到的文件对象
const _this = this // 保存this
for (let i = 0; i < files.length; i++) { //对文件数组对象进行迭代循环
const reader = new FileReader() this.imgfiles.push(files[i])
reader.readAsDataURL(files[i])
reader.end = function() { console.log(this.result)
_this.imgs.push(this.result)
}
}对不要的图片进行删除?
获取图片数组下标,使用数组 slice方法进行删除
获取下标:
v-for 的i就代表了数组的下标,因为我们不仅需要删除图片数组,还需要删除文件数组,删除操作:
del(i) { this.imgfiles.splice(i, 1) this.imgs.splice(i, 1) this.imgsChange()
},将获取到的文件对象向父组件进行广播
imgsChange() { this.$emit('imgsChange', this.imgfiles) //广播事件名:imgsChange,参数 this.imgfiles
}下面是我封装的组件的完整代码,没有进行更多的操作,仅仅是把选择的图片可以本地预览,删除,增加
0' class="flex">.img-box{ position: relative; border:1px solid #e6e6e6; margin-right: 20px; padding-top:30px; background: #f6f6f6; img{ width: 160px; } span { position: absolute; top:5px; right: 10px; color: red; } } .img-file{ height: 190px; width: 190px!important; display: flex; align-items: center; font-size: 30px; text-align: center; border: 1px #e6e6e6 dashed; justify-content: center; margin: 0; }
原文出处:https://www.cnblogs.com/yuanchenchun/p/9492112.html



