我正在使用 Vue 和 Axios 来显示进度条。 uploadProgress
是我的 Vue 实例中的数据键。当我尝试使用内部函数设置它时,它只是说它未定义。这是我的代码的简化版本:
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
?
最佳答案
您已将 uploadProgress
添加到函数 someVueMethod
的上下文中,但尝试在函数 onUploadProgress
的上下文中访问它。您需要像这样使用原始上下文。
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
})
}
关于javascript - Vue : How to set data from within an "inner" function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48002841/