vant 组件库中的 图片上传组件(多张图片上传,删除图片传自定义参数)
图片上传前,限制图片格式。图片上传后,上传七牛云接口返回图片url,赋值给图片路径变量。图片删除坑:vant上传组建中内置的删除事件,默认携带两个参数,file和detail,detail中包括name和index字段。想要携带自定义参数,绑定事件时候用箭头函数:before-delete = " (file,detail) => {delImg (自定义参数)}"
- html部分
- js部分
图片上传前,限制图片格式。图片上传后,上传七牛云接口返回图片url,赋值给图片路径变量。
图片删除
坑:vant上传组建中内置的删除事件,默认携带两个参数,file和detail,detail中包括name和index字段。
想要携带自定义参数,绑定事件时候用箭头函数
:before-delete = " (file,detail) => {delImg (file,detail,自定义参数)}"
文字说明,方便复制复用
html部分:
<van-uploader
v-model="item.fileList"
:max-count="6"
:before-read="beforeRead"
:after-read="(file)=>afterRead(file,index)"
:before-delete="(file,detail)=>delImg(file,detail,index)"
>
<div class="flex flex-col flex-nowrap justify-center items-center w-160 h-160 rounded-16 bg-white">
<div>
<van-image
class="w-69 h-59"
:src="`${CDN_DOMAIN}/images/form/default.png`"
fit="cover"
:show-loading="false"
:show-error="false"
alt="default"
/>
</div>
<div class="flex flex-row flex-nowrap justify-center items-center mt-15">
<span class="text-tip text-26 font-500">添加照片</span>
</div>
</div>
</van-uploader>
js部分:
beforeRead(file) {
const type = ['image/jpeg', 'image/png']
const isImage = type.includes(file.type)
const isLt2M = file.size / 1024 / 1024 < 2
if (!isImage) {
this.$toast('上传图片格式不正确')
}
if (!isLt2M) {
this.$toast('图片大小不能超过 2MB!')
}
return isImage && isLt2M
},
afterRead(file, index) {
const params = {
token: this.token,
file: file.file,
}
console.log(params)
this.$yghttp.post(`/api/common/uploadIo`, params).then((res) => {
this.isLoading = false
this.loadingText = '加载中...'
const {
data, code, msg,
} = res
if (code === 1) {
this.formData.experiences[index].pic.push(data.url)
console.log(this.formData.experiences[index].pic,'pic')
} else {
this.$toast(msg)
}
console.log(
this.formData, 123, index,
)
})
},
// 删除图片前的回调,可以返回Promise
delImg(file, detail, index) {
return new Promise((resolve, reject) => {
this.$dialog
.confirm({ message: '确认删除图片?' })
.then(() => {
// 存放图片的数组
this.formData.experiences[index].pic.splice(detail.index, 1)
this.$toast.success('删除成功')
console.log(detail, index, this.formData.experiences[index].pic)
resolve()
})
.catch(error => {
this.$toast.fail('已取消')
reject(error)
})
})
},
更多推荐
所有评论(0)