Vue:如何从 "inner" 函数中设置数据?
Vue: How to set data from within an "inner" function?
我正在使用 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
})
}
我正在使用 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
})
}