【问题标题】:Vue: How to set data from within an "inner" function?Vue:如何从“内部”函数中设置数据?
【发布时间】:2023-04-02 14:15:01
【问题描述】:

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

【问题讨论】:

    标签: javascript vue.js axios


    【解决方案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
      })
    }
    

    【讨论】:

    • 是的!谢谢你。我尝试了几种类似的方法,试图在其中获取上下文,但无法完全理解。这非常有效。谢谢!
    猜你喜欢
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 2020-06-05
    • 2021-10-01
    • 2021-12-14
    • 1970-01-01
    相关资源
    最近更新 更多