Vue.js 上传文件时 this.safetyPhotolist[fileListLen] 无法获取内容的解决方法
在 Vue.js 中使用 $request.uploadFile 上传文件时,可能会遇到在回调函数中无法获取 this.safetyPhotolist[fileListLen] 内容的问题。这是因为在 uploadFile 的回调函数中,this 指向发生了变化,不再是外层函数的 this,而是 uploadFile 函数内部的 this。
为了解决这个问题,可以将外层函数的 this 保存在一个变量中,然后在回调函数中使用该变量来访问 this.safetyPhotolist。例如:
if(type == 'safetyRecord'){ let fileListLen = this.safetyPhotolist.length let self = this // 保存外层函数的 this 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) self.safetyPhotolist[fileListLen] = self.imgpath+resdata.data.fileId // 使用 self 访问 this.safetyPhotolist console.log(this.startinfo.safetyRecordPhoto) } }else{ //上传失败,删除状态 if(type == 'safetyRecord'){ self.safetyPhotolist.splice(fileListLen, 1) // 使用 self 访问 this.safetyPhotolist }
this.$refs.uToast.error('上传失败') } })
通过使用 self 变量,可以在回调函数中正确访问 this.safetyPhotolist,从而解决无法获取内容的问题。
原文地址: https://www.cveoy.top/t/topic/lyEs 著作权归作者所有。请勿转载和采集!