由于公司最近有图片上传的业务需求,就记录下,以便自己回头看看。不能选择相同的图片。
废话不多说,请看代码:
1.标签节点代码
<div class="wrapper">
<div class="uploader">
<div>图片上传</div>
<div>{{imgUrls.length || '0'}}/4张</div>
</div>
<div class="upload-picture" ref="photos">
<ul v-show="imgUrls.length!=0">
<li v-for="(item,index) in imgUrls"
:key="index"
class="addPicture">
<!-- 展示上传的图片 -->
<img :src="item" class="img1" @click="handleBig(index)">
<!-- 展示删除图片的按钮 -->
<img src="../img/clear.jpg" class="img2" @click="handleCancel(item)">
</li>
</ul>
<input type="file"
ref="file"
hidden
accept="image/*"
@change="getPicture($event)">
<button @click="$refs.file.click()"
v-show="showInputImg">+</button>
</div>
</div>
2.js逻辑代码块
<script>
import {ImagePreview} from 'vant'
export default {
data(){
return {
// 上传图片的数组
imgUrls:[],
// 点击放大图片的预览数组
preImage:[]
}
},
computed: {
showInputImg () {
return this.imgUrls.length < 4;
}
},
methods: {
getPicture (e) {
//预览图片
let src = window.URL.createObjectURL(e.target.files[0]);
this.imgUrls.push(src);
this.preImage.push(src);
// ImagePreview(this.uploadImg);
console.log('111111')
console.log(this.imgUrls)
//将图片文件转化成base64格式图片
var reader = new FileReader();
reader.onload = (e) => {
//e.target.result 就是从本地读取的图片的base64格式,将它上传给服务器即可
}
reader.readAsDataURL(e.target.files[0])
},
handleCancel(item){
this.imgUrls=this.imgUrls.filter((ele)=>{
return ele!=item
})
//解决取消上传文件后再选择相同图片不触发 change 事件
this.$refs.file.value = null;
},
//点击预览放大的图片
handleBig(index){
ImagePreview({
images:this.preImage,
closeable:true,
startPosition:index
})
console.log(this.preImage)
}
}
}
</script>
3.样式代码
.wrapper{
padding:0 30px;
}
input {
display: none;
}
.uploader{
display:flex;
justify-content: space-between;
font-size:30px;
margin-bottom:15px;
}
.upload-picture{
display: flex;
height: 120px;
line-height: 120px;
padding: 10px 0;
border-bottom: 1px solid #ccc;
overflow: hidden;
}
.upload-picture ul {
display: flex;
}
.upload-picture ul li {
margin-right: 10px;
}
.upload-picture .addPicture .img1 {
height: 100px;
width: 100px;
}
.upload-picture .addPicture .img2{
height:22px;
width:22px;
position:relative;
bottom:90px;
right:10px;
}
.upload-picture button {
height: 100px;
width: 100px;
line-height: 100px;
font-size: 50px;
border: 1px dashed red;
color: #333;
background-color: #ccc;
}
这仅仅是前端的代码,并没有把图片保存到后台,也就是并没有和后端做交互,等业务开发完再来补充,谢谢。