Vue.js 上传文件时 this 指向问题及解决方法

在 Vue.js 中,上传文件时,可能会遇到 this 指向问题,导致无法正确访问组件实例的属性或方法。

问题描述:

以下代码片段展示了在上传文件成功后更新图片列表时遇到的问题:

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 函数内部,this 指向的是函数本身,而不是组件实例。因此,无法访问组件实例中的 safetyPhotolist 属性。

解决方案:

this 保存在一个变量中,然后在函数内部使用该变量。

let vm = this;  
this.$request.uploadFile(res.tempFilePaths[0]).then(res => {  
	// 在函数内部使用 vm 代替 this  
	vm.safetyPhotolist[fileListLen] = vm.imgpath + resdata.data.fileId;  
	// ...  
});  

修改后的代码:

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)  
}

let vm = this;  
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'){  
			vm.startinfo.safetyRecordPhoto.push(img)  
			vm.safetyPhotolist[fileListLen] = vm.imgpath+resdata.data.fileId  
			console.log(vm.startinfo.safetyRecordPhoto)  
		}  

	}else{  
		//上传失败,删除状态  
		if(type == 'safetyRecord'){  
			vm.safetyPhotolist.splice(fileListLen, 1)  
		}  
		  
		this.$refs.uToast.error('上传失败')  
	}  
})  

通过这种方式,可以确保在 uploadFile 函数内部正确访问组件实例的属性和方法。

总结:

在 Vue.js 中,上传文件时,需要特别注意 this 指向的问题。将 this 保存在一个变量中,并在函数内部使用该变量,可以有效地解决这个问题。

Vue.js 上传文件时 this 指向问题及解决方法

原文地址: https://www.cveoy.top/t/topic/lyFA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录