Vue.js 中 uploadFile 方法获取不到数组元素的问题及解决方法
在 Vue.js 项目中,使用 uploadFile 方法上传文件时,有时会遇到获取不到 this.safetyPhotolist[fileListLen] 内容的问题。这可能是因为在调用 uploadFile 方法之前,safetyPhotolist 数组长度已经被改变了。
例如,在以下代码中:
if(type == 'safetyRecord') {
let fileListLen = this.safetyPhotolist.length
this.safetyPhotolist.push('/static/images/loading.gif')
console.log(type == 'safetyRecord')
console.log(fileListLen)
console.log(this.safetyPhotolist.length)
}
this.$request.uploadFile(res.tempFilePaths[0]).then(res => {
let resdata = JSON.parse(res.data)
console.log(resdata.code)
if(resdata.code == 200) {
let img = {}
img.fileId = resdata.data.fileId
img.fileName = resdata.data.fileName
img.fileUrl = resdata.data.fileUrl
if(type == 'safetyRecord') {
this.startinfo.safetyRecordPhoto.push(img)
this.safetyPhotolist[fileListLen] = this.imgpath+resdata.data.fileId
console.log(this.startinfo.safetyRecordPhoto)
}
} else {
//上传失败,删除状态
if(type == 'safetyRecord') {
this.safetyPhotolist.splice(fileListLen, 1)
}
this.$refs.uToast.error('上传失败')
}
})
在 if(type == 'safetyRecord') 中,首先将 loading.gif 加入 safetyPhotolist 数组,然后调用 uploadFile 方法,上传成功后再将上传的图片信息添加到 safetyRecordPhoto 数组中,并将 safetyPhotolist 中对应位置的 loading.gif 替换为上传成功的图片。
但是,在上传成功之前,safetyPhotolist 数组的长度已经被改变了,因此在上传成功后使用 fileListLen 可能已经不再是正确的位置,从而导致获取不到对应的值。
解决方法:
建议使用其他方式记录或获取需要的位置信息,例如:
- 使用一个单独的变量记录 loading.gif 的位置。
- 在上传图片之前,将需要替换的图片信息存储在一个新的数组中,上传完成后再使用这个数组更新 safetyPhotolist 数组。
通过以上方法,可以避免在上传过程中数组长度发生变化导致获取不到元素的问题。
原文地址: https://www.cveoy.top/t/topic/lyFv 著作权归作者所有。请勿转载和采集!