<template>
<div class="app-container">
<van-form @submit="onSubmit">
<div>完成描述</div>
<van-field
v-model="deliveryDescription"
rows="3"
autosize
type="textarea"
placeholder="请输入"
:rules="[{ required: true, message: '请填写完成描述' }]"
/>
<!-- 文件上传完毕后会触发 after-read 回调函数,获取到对应的 file 对象 -->
<!-- 通过 v-model 可以绑定已经上传的文件列表,并展示文件列表的预览图 -->
<!-- max-count 限制上传文件的数量,上传数量达到限制后,会自动隐藏上传区域 -->
<van-uploader :after-read="upload" v-model="fileList" :max-count="5"/>
<div style="margin: 16px">
<van-button block class="accept" native-type="submit">提交</van-button>
</div>
</van-form>
</div>
</template>
<script>
import { deliveryTask, uploadFile } from '@/api/task/task.js';
export default {
data() {
return {
// 已上传的文件列表
fileList: [],
deliveryDescription: '',
deliveryAttachment: '',
ids: [],
// 上传成功才能提交的开关数组
uploadFileList: []
};
},
methods: {
// 表单提交按钮
async onSubmit() {
// 如果上传成功的数组长度小于上已上传数组的长度并且检索已上传的列表是否有这个图片的guid,请等待图片上传完成后提交
// every() 方法用于检测数组所有元素是否都符合指定条件,有一个元素不满足,则整个表达式返回 false;如果所有元素都满足条 件,则返回 true
if (
this.uploadFileList.length < this.fileList.length &&
this.fileList.every(item => item.guid)
) {
this.$toast.fail('请等待图片上传完成后提交');
} else if ( // 如果上传成功的数组长度大于上已上传数组的长度或者上传成功的数组长度等于上已上传数组的长度,进行上传操作
this.uploadFileList.length > this.fileList.length ||
this.uploadFileList.length == this.fileList.length
) {
// 遍历上传成功后的数组
this.uploadFileList.forEach(item1 => {
// 遍历上传的数组
this.fileList.forEach(item2 => {
// 如果上传成功后的图片guid等于上传的图片guid,把图片guid添加到另一个ids的数组里面
if (item1.guid == item2.guid) {
this.ids.push(item2.guid);
}
});
});
// 去重复的图片
this.ids = [...new Set(this.ids)];
// 这里是把上传的图片路径用逗号分隔(我们后台需要我用逗号分隔,这里依据个人情况)
this.deliveryAttachment = this.ids.join(',');
// 调用列表的接口,把上传的文件传给后台
const res = await deliveryTask({
deliveryDescription: this.deliveryDescription,
orderGuid: this.$route.query.id,
deliveryAttachment: this.deliveryAttachment
});
// 成功之后的提示信息
if (res.data.success) {
this.$toast.success(res.data.message);
// this.$router.replace跳转到上上一个页面。上一个记录是不存在的
this.$router.replace({ name: 'deliverSuccess' });
} else {
this.$toast.fail('订单已交付,请勿重复点击');
}
} else {
this.$toast.fail('请等待图片上传完成后提交');
}
},
// 文件上传完毕后会触发 after-read 回调函数,获取到对应的 file 对象
async upload(file) {
// 这时候我们创建一个formData对象实例
const formData = new FormData();
// 通过append方法添加需要的file
// 这里需要注意 append(key, value)来添加数据,如果指定的key不存在则会新增一条数据,如果key存在,则添加到数据的末尾
formData.append('file', file.file);
// 调用uploadFile上传的接口
const res = await uploadFile(formData);
// 上传文件的guid和后台返回的guid一样,通过push方法把上传的文件存放到上传成功才能提交的数组里面
file.guid = res.data.result.guid;
this.uploadFileList.push(file);
}
}
};
</script>
<style scoped lang="scss">
.app-container {
padding: 10px;
.van-field {
margin: 10px 0;
}
.accept {
height: 40px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 5px;
background-color: #ff9c0a;
color: #fff;
}
}
</style>