在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
本文实例为大家分享了Vant Uploader实现上传一张或多张图片组件,供大家参考,具体内容如下 html部分 <template> <div class="contWrap"> <van-uploader v-model="fileList" :multiple="true" :before-read="beforeRead" :after-read="afterRead" :before-delete="delUploadImg" upload-icon="plus" > <!-- 注:这里是自定义上传样式 --> <!-- <p> <van-icon name="plus" color="#07c160" size=".5rem" /> 上传照片 </p> --> </van-uploader> </div> </template> js部分 <script> import axios from "axios"; export default { name: "uploadImages", data() { return { fileList: [], uploadUrl: "/api/upload/fileUpload", headers: { token: this.$store.state.account.token, }, }; }, methods: { // 返回布尔值 beforeRead(file) { if (file instanceof Array) { //判断是否是数组 file.forEach((v) => { this.checkFile(v); }); } else { this.checkFile(file); } return true; }, //图片类型检查 checkFile(file) { const format = ["jpg", "png", "jpeg"]; const index = file.name.lastIndexOf("."); const finalName = file.name.substr(index + 1); if (!format.includes(finalName.toLowerCase())) { Toast("请上传" + format.join(",") + "格式图片"); return false; } }, afterRead(file) { // 此时可以自行将文件上传至服务器 if (file instanceof Array) { file.map((v) => { v.status = "uploading"; v.message = "上传中..."; this.uploadImg(v); }); } else { file.status = "uploading"; file.message = "上传中..."; this.uploadImg(file); } }, //上传 uploadImg(file) { const formData = new FormData(); formData.append("file", file.file); axios .post(this.uploadUrl, formData, { headers: this.headers, }) .then((res) => { if (res.data) { if (file instanceof Array) { //判断是否是数组 file.map((v, i) => { v.status = "success"; v.message = ""; v.url = res.data[i]; }); } else { file.status = "success"; file.message = ""; file.url = res.data.uploadUrl; } } }) .catch((err) => { this.$notify({ type: "warning", message: "上传失败", }); }); }, //删除 delUploadImg(item) { this.fileList = this.fileList.filter((v) => v.url != item.url); } }, }; </script> 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持极客世界。 |
请发表评论