二次封装van-uploader

二次封装van-uploader

  • 直接返回图片列表
  • 会等待所有图片上传成功
  • 图片上传状态显示
// uploadImgs.vue
<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)
/**
 * @description  基于vue2,vant2上传图片组件
 * @property {Array} imgList 图片列表
 * @event {Function} imgUploadOk 图片上传成功回调
 * @event {Function} deleteImg 删除图片回调
 */
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>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值