多张图片上传(未上传展示提示图片)
因为使用Vant UI组件库中 Uploader 组件不包含将文件上传至服务器的接口逻辑,所以需要进行二次封装,让他可以支持多图片上传
内部的上传图片的封装
<template v-if="['uploaderImg'].indexOf(item.type) !== -1">
<van-field :name="item.type" :label="item.name">
<template #input>
<van-uploader
v-model="searchData[item.prop]" // 上传图片赋值,双向绑定
:max-count="item.maxCount" // 限制上传的图片数量
:before-read="beforeRead" // 上传前的函数-----限制上传图片格式
:after-read="afterRead" // 商户后的函数-----上传之后让展示上传loading状态,发起请求,上传成功,展示上传成功
@click-preview="clickPreview" // 点击上传的图片,全屏预览当前图片
@click.native.stop="click(item)" // 获取当前上传的绑定字段,上传之后$emit出去(重点)
>
<div class="van-uploader__upload">
<!-- 显示自定义上传的提示图片 -->
<span v-if="item.modelImg" class="van-icon"><img :src="item.modelImg" alt="" /></span>
<span v-else></span>
<input
multiple="multiple"
type="file"
accept="image/*"
class="van-uploader__input"
/>
</div>
</van-uploader>
</template>
</van-field>
</template>
<script>
export default {
name: 'Home',
components: {
SeForm
},
data () {
return {}
},
methods:{
//上传前的方法
beforeRead (file) {
console.log(1234)
// accept=".png,.PNG,.jpeg,.jpg,.JPG"
if (
file.type !== 'image/jpeg' &&
file.type !== 'image/png' &&
file.type !== 'image/jpg' &&
file.type !== 'image/gif'
) {
this.$toast('请上传 jpg,png 格式图片')
return false
}
return true
},
//上传后的方法
afterRead (file) {
file.status = 'uploading'
file.message = '加载...'
this.$emit('uploadImg', [file, this.propType])
},
//点击获取当前图片的v-model值 (用于区别每一个上传项)
click (item) {
this.propType = item.prop
},
// 点击当前图片全屏预览图片
clickPreview (val) {
ImagePreview({
images: [val.url],
closeable: true
})
},
}
}
</script>
外部拿到$emit 的方法
uploadImg (val) {
const formData = new FormData()
formData.append('file', val[0].file)
this.$http.formDetails.uploadImg(formData).then(res => {
val[0].status = 'done'
val[0].message = '上传成功' //修改成上传成功的状态
if(val[1]==='certFirstPage') { // 将后端返回的地址,赋值,一一对应的显示在页面上
this.certFirstPage = res.result
}else if(val[1]==='certAnnualInspectPage') {
this.certAnnualInspectPage = res.result
}else if(val[1]==='certHandLicense') {
this.certHandLicense = res.result
}else if(val[1] === 'certRemarkPage') {
this.certRemarkPage = res.result
}
const params = { // 修改图片的接口
certFirstPage: this.certFirstPage,
certAnnualInspectPage: this.certAnnualInspectPage,
certHandLicense: this.certHandLicense,
certRemarkPage: this.certRemarkPage
}
this.$http.formDetails.editUser(params).then(res=>{})
})
},
浙公网安备 33010602011771号