Vue.js 上传图片获取不到数组元素问题及解决方案
在 Vue.js 中使用 uploadFile 方法上传图片时,有时会遇到获取不到数组元素的问题。例如,以下代码段中,在调用 uploadFile 方法后,无法获取到 this.safetyPhotolist[fileListLen] 的值。
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('上传失败')
}
})
问题原因:
该问题主要是因为 uploadFile 方法是异步执行的,而 console.log(this.safetyPhotolist.length) 语句是在调用 uploadFile 方法后立即执行的。此时,uploadFile 方法还未完成,safetyPhotolist 数组还没有被更新,因此无法获取到对应的值。
解决方法:
-
将 console.log(this.safetyPhotolist.length) 语句放在 uploadFile 方法的回调函数中,以确保在数组更新后获取值。
-
使用 async/await 等方法控制异步执行顺序,以确保在获取值之前,uploadFile 方法已经完成。
例如,将代码修改为以下形式:
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 => {
// ... (处理上传结果)
console.log(this.safetyPhotolist.length) // 在回调函数中获取数组长度
})
总结:
在进行异步操作时,需要格外注意执行顺序,避免出现获取不到值的问题。通过将相关代码放在回调函数中,或者使用异步控制机制,可以有效解决此类问题。
原文地址: https://www.cveoy.top/t/topic/lyFt 著作权归作者所有。请勿转载和采集!