Glenn
Glenn

Reputation: 5081

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

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
  })
}

How can I set uploadProgress from within that inner function?

Upvotes: 0

Views: 124

Answers (1)

Sandip Ghosh
Sandip Ghosh

Reputation: 719

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
  })
}

Upvotes: 1

Related Questions