Vant框架实现图片上传
一、Vant框架简介
是有赞前端团队基于有赞统一的规范实现的 Vue 组件库,提供了一整套 UI 基础组件和业务组件。
中文文档 | 在线预览
二、图片上传案例实现
上传按钮的样式存在不足;上传不同名称的同一张图片会有bug;求教,谢谢。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>vant_demo</title>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<!-- 引入样式文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vant@2.10/lib/index.css" />
<!-- 引入 Vue 和 Vant 的 JS 文件 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vant@2.10/lib/vant.min.js"></script>
<style>
body {
margin: 0;
height: 100%;
}
[v-cloak] {
display: none;
}
/* 为了美观,修改一下vant框架的样式 */
.van-uploader__wrapper > div{
/* 每行3张照片的宽度等于29.99=[100-(1.65*6)]/3 */
/* 每行5张照片的宽度等于16.7=[100-(1.65*10)]/5 */
/* imgscss()函数也需要改 */
width: 29.99%;
margin: 0 1.65% 8px 1.65%;
}
.van-uploader__preview div:first-child{
width: 100%;
height: 100%;
}
.van-uploader__upload{
/* 上传按钮的样式 */
}
</style>
</head>
<body>
<div id="demo">
<div style="margin: 20px 5% 20px 5%;background-color: #008080;" id="imgs">
<van-uploader style="width: 100%;" v-model="fileList" :deletable="deletable" multiple :after-read="afterRead" :max-size="500 * 1024" @oversize="onOversize" :max-count="10"/>
</div>
</div>
</body>
<script>
var vm = new Vue({
el: '#demo',
data:{
fileList: [], //预览图片列表(要上传到后台的Base64数组)
deletable:true,
repeatImgs: 0 //已经发现的重复图片数目
},
mounted() {
this.imgscss()
},
methods: {
//读取到file这张图片后
afterRead(file) {
//一次上传单张,file是一个对象
if (!Array.isArray(file)) {
this.imgHandleFun(file.content, 0, 1);
this.repeatImgs = 0
}
//一次上传多张,file是一个数组
else {
for (let i = 0; i < file.length; i++) {
this.imgHandleFun(file[i].content, i, file.length);
}
this.repeatImgs = 0
}
this.imgscss()
},
//图片处理函数
imgHandleFun(content, index, len) {
const that = this
for(let i = 0; i < that.fileList.length - len + that.repeatImgs; i++){
//因为删除重复照片后,that.fileList.length会变化,
//that.fileList.length - len + that.repeatImgs就是为了即使删除了,也能保持这次上传之前的每一张图片
if(that.fileList[i].content.split(",")[1] == content.split(",")[1]){
that.fileList.splice(that.fileList.length - len + index, 1);
vant.Toast('已筛除您之上传的同张图片');
that.repeatImgs += 1
}
}
},
onOversize(file) {
vant.Toast('文件大小不能超过 500kb');
},
//样式矫正
imgscss(){
let w = $('#imgs').width();
$('.van-uploader__preview').height(w * 0.299);
$('.van-uploader__upload').height(w * 0.299);
}
}
})
</script>
</html>