二次封装van-uploader
- 直接返回图片列表
- 会等待所有图片上传成功
- 图片上传状态显示
<template>
<van-uploader
v-model="fileList"
:after-read="afterRead"
v-bind="$attrs"
@delete="deleteImg" />
</template>
<script>
import { Uploader } from 'vant'
import Vue from 'vue'
Vue.use(Uploader)
export default {
props: {
imgList: {
type: Array,
default: () => []
}
},
data() {
return {
fileList: this.imgList,
uploadedCount: 0,
totalFilesToUpload: 0
}
},
methods: {
afterRead(file) {
this.totalFilesToUpload = file.length || 1
if (file.length > 0) {
file.forEach(item => {
item.status = 'uploading'
item.message = '上传中...'
this.uploadImg(item).then(() => {
this.uploadedCount++
this.checkAllUploaded()
}).catch(() => {
this.uploadedCount++
this.checkAllUploaded()
})
})
} else {
file.status = 'uploading'
file.message = '上传中...'
this.uploadImg(file).then(() => {
this.uploadedCount++
this.checkAllUploaded()
}).catch(() => {
this.uploadedCount++
this.checkAllUploaded()
})
}
},
uploadImg(file) {
const formData = new FormData()
formData.append('file', file.file)
return new Promise((resolve, reject) => {
this.$API.home.upload
.post(formData)
.then((data) => {
if (data.response?.id) {
file.status = 'done'
file.message = '上传成功'
file.url = imgURL + data.response.id + '/0/0'
file.id = data.response.id
} else {
file.status = 'error'
file.message = '上传失败'
file.id = ''
}
resolve()
})
.catch(() => {
reject()
})
})
},
checkAllUploaded() {
if (this.uploadedCount === this.totalFilesToUpload) {
this.$emit('imgUploadOk', this.fileList)
}
},
deleteImg() {
this.$emit('deleteImg', this.fileList)
}
}
}
</script>