Vue js“this”被 image.onload“this”覆盖

Geo*_*rge 5 javascript node.js vue.js vuejs2

我有一个 vue 应用程序。我用来this.data访问它的数据变量和方法。

在某种方法中,我必须使用 img.onload 来获取图像的宽度。但是现在有 2 个“ this ”,vue js 方法和变量现在不起作用。我需要一个替代解决方案,以便两者都能工作。

vueMethod(url) {
 var img = new Image();
 img.onload = function() {
  this.size = {this.width,this.height}  //size is a vue variable
 }
 img.src = url;
}
Run Code Online (Sandbox Code Playgroud)

Bou*_*him 4

您可以分配给调用函数之前 this调用的变量,如下所示vmimg.onload

vueMethod(url) {
  var img = new Image();
  let vm = this;
  img.onload = function() {
    vm.size = { this.width, this.height }  //size is a vue variable
  }
  img.src = url;
}
Run Code Online (Sandbox Code Playgroud)

  • 使用箭头函数会更有意义 (2认同)