javascript - Vue : How to set data from within an "inner" function?

标签 javascript vue.js axios

我正在使用 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/

相关文章:

javascript - 如何从android webview调用AngularJS服务代码?

javascript - div 内表格的固定列

javascript - 使数字输入值大于50时显示 "∞"

vue.js - 无法在Vuejs中访问ag-Grid API

Javascript - 将匿名函数传递给 Promise.all

javascript - 使用 knockout 创建的 jquery 选择选项

vue.js - `v-bind` 的简写,以防子组件属性名称等于传递的对象名称

typescript - 如何使用 TypeScript 在 Vue.js 中使用 Provide/Inject

ajax - 无法读取 Reactjs 中未定义的属性

javascript - 将 axios 数据传递给 View 模板