本文介绍了意见:如何从“内部"设置数据?功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Vue和Axios显示进度条. uploadProgress
是我的Vue实例中的数据键.当我尝试使用内部函数进行设置时,它只是说其未定义.这是我的代码的简化版本:
I'm using Vue and Axios to display a progress bar. uploadProgress
is a data key in my Vue instance. When I try to set it using an inner function, it just says its undefined. Here's a simplified version of my code:
someVueMethod() {
this.uploadProgress = 0 // this works
let config = {
onUploadProgress(progress) {
// this doesn't work, error says uploadProgress is undefined
this.uploadProgress += progress.loaded / progress.total
}
}
axios.put(url, file, config).then(res => {
// handle the response
})
}
如何从该内部函数中设置 uploadProgress
?
How can I set uploadProgress
from within that inner function?
推荐答案
您已将 uploadProgress
添加到函数 someVueMethod
的上下文中,但尝试在其中访问函数 onUploadProgress
的上下文.您需要使用这样的原始上下文.
You have added uploadProgress
to the context of the function someVueMethod
, but are trying to access it in the context of the function onUploadProgress
. You need to use the original context like this.
someVueMethod() {
var self = this; //store the context of someVueMethod
this.uploadProgress = 0 // this works
let config = {
onUploadProgress(progress) {
// use the original context using self
self.uploadProgress += progress.loaded / progress.total
}
}
axios.put(url, file, config).then(res => {
// handle the response
})
}
这篇关于意见:如何从“内部"设置数据?功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!