Vue:如何在“内部”功能中设置数据?

时间:2017-12-28 06:44:13

标签: javascript vue.js axios

我正在使用Vue和Axios来显示进度条。 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 }) } 是我的Vue实例中的数据键。当我尝试使用内部函数设置它时,它只是说它未定义。这是我的代码的简化版本:

uploadProgress

如何在内部函数中设置<div class="col-xs-4 btn-group" id="challenge-radio-btn"> <label class="radio-inline"> <input type="radio" ng-model="trigger" ng-value=false name="{{path.id}} notChallengeTriggr" ng-change = "onChange(x,y,z,w,a)" ng-disabled="campaign.editnotscheduled || ischallengeTrigger" checked> No </label> <label class="radio-inline"> <input type="radio" ng-model="trigger" ng-value=true name="{{path.id}} challengeTriggr" ng-change = "onChange(x,y,z,w,a)" ng-disabled="campaign.editnotscheduled || ischallengeTrigger"> Yes </label> </div>

1 个答案:

答案 0 :(得分:1)

您已将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
  })
}