upload-image-multiple.vue 2.59 KB
<template>
	<view>
		<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" :maxCount="maxCount"/>
	</view>

</template>

<script>
	import cache from '@/utils/cache';
	import config from '@/config';
	
	const url = config.uploadHost;
	const userInfo = cache.get('USERINFO')
	const header = {
	  'Authorization': 'Bearer ' + userInfo?.accessToken
	};
	
	export default {
		// v-bind不支持 后续只能单个props传入
		props: {
			value: String,
			maxCount: [String, Number],
		},
		data() {
			return {
				fileList: this.value
			}
		},
		watch: {
			value: {
				handler(val) {
					this.fileList = val? val.split(',').map(i => ({
						url: i
					})) : []
				},
				immediate: true,
			},
			fileList(val) {
				if (val) {
					this.$emit('input', val.map(i => i.url).join(',') || '')
				}

			}
		},
		methods: {
			// 新增图片
			async afterRead(event) {
				const file = event.file || {}
				const url = file.url || ''
				const result = await this.uploadFilePromise(url)
			},
			uploadFilePromise(filePath) {
				return new Promise((resolve, reject) => {
					uni.showLoading({ title: '上传中...' });
					uni.uploadFile({
					  url,
					  header,
					  filePath,
					  name: 'file',
					  formData: {
					    module: 'dispatch-ma',
					    category: 'opr'
					  },
					  success: (response) => {
					    uni.hideLoading();
					    const { statusCode } = response;
					    const data = JSON.parse(response.data.replace(/\ufeff/g, '') || '{}');
					    const result = data.result || [];
					    if (statusCode == 200) {
								this.fileList.push({url: result[0]})
					    } else {
					      if (result[0]) {
					        this.fileList.push({url: result[0]})
					      } else {
					        setTimeout(() => {
					          uni.showToast({ title: data.message || response.errMsg || '上传失败', icon: 'none' });
					        }, 1500);
					      }
					    }
					  },
					  fail: () => {
					    uni.hideLoading();
					    setTimeout(() => {
					      uni.showToast({ title: '系统异常', icon: 'none' });
					    }, 1500);
					  }
					});
				})
			},
			// 删除
			deletePic(event) {
				uni.showModal({
				  title: '提示',
				  content: '确定删除这张图片吗?',
				  // #ifdef MP-DINGTALK
				  confirmButtonText: '确定',
				  cancelButtonText: '取消',
				  // #endif
				  success: (res) => {
				    if (res.confirm) {
							const {index} = event || {}
				      this.fileList.splice(index, 1)
				    }
				  }
				});
			}
		}
	}
</script>

<style lang="scss">
	.u-upload__button{
		border-radius: $radius-md;
		box-shadow: $shadow-normal;
	}
</style>