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

时间:2018-12-05 14:20:26

标签: 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;
}

5 个答案:

答案 0 :(得分:1)

您可以按如下所示在调用this函数之前将vm分配给名为img.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;
}

答案 1 :(得分:1)

您可以使用arrow functiondocumentation)来保持合并范围:

vueMethod(url) {
  var img = new Image();
  img.onload = () => {
    this.size = {img.width, img.height}
  }
  img.src = url;
}

在此示例中,this的引用与您在var img旁边使用的引用相同

答案 2 :(得分:0)

var that = this;放入img函数中。

这将为您提供函数的作用域,或在调用函数时将其绑定,例如

vueMethod("url").bind(this)

答案 3 :(得分:0)

您应该将Vue等距保存到img.onload范围之外的变量中 尝试:

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

答案 4 :(得分:0)

因此,当您使用带有关键字function的函数时,它将为此创建新的作用域,以供参考以下示例

const obj = {
  size: 10,
  testFunc() {
   console.log(this, 'now obj')

   const func = function () {
     // this now refers to function its currently in
   }
   const otherFunc = () => console.log(this, 'refers to obj still')
  },
  testFunc2: () => {
    console.log(this, 'now window')
  }
}

任何问题都让我知道,我很乐意提供帮助

const obj = {
  size: 10,

  vueMethod(url) {
    console.log(this.size, 'this now refers to obj')
    const img = new Image();
    const self = this;

    img.onload = function() {
      console.log(this, 'this now refers to img')
      console.log(self.size, 'but you can reassign this to a var outside the scope');

      self.size = {
        width: this.width,
        height: this.height
      }
    };
    // mocking the onload dont include this
    img.onload();
    img.src = url;
  }
}

obj.vueMethod()