Vant Uploader實現上傳一張或多張圖片元件
阿新 • • 發佈:2021-09-17
本文例項為大家分享了Vant Uploader實現上傳一張或多張圖片元件,供大家參考,具體內容如下
html部分
www.cppcns.com<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>
部分
<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,formDhttp://www.cppcns.comata,{ headers: this.headers,}) .then((res) => { if (res.data) { if (file instanceof Array) { //判斷是否是陣列 file.map((v,i) => { v.status = "success"; v.message = ""; v.urlhttp://www.cppcns.com= res.data[i]; }); } else { file.status = "success"; file.message = ""; file.url vIJYCaeg= res.data.uploadUrl; } } }) .catch((err) => { this.$notify({ type: "warning",message: "上傳失敗",}); }); },//刪除 delUploadImg(item) { this.fileList = this.fileList.filter((v) => v.url != item.url); } },}; </script>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。