【问题标题】:Vue js "this" is overridden with image.onload "this"Vue js "this" 被 image.onload "this" 覆盖
【发布时间】:2019-05-07 03:30:43
【问题描述】:

我有一个 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;
}

【问题讨论】:

  • 所以使用函数会创建一个新范围

标签: javascript node.js vue.js vuejs2


【解决方案1】:

您可以在调用img.onload 函数之前将this 分配给一个名为vm 的变量,如下所示

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

【讨论】:

  • 使用箭头函数会更有意义
  • this.size 不起作用?因为这也指图像
  • 认为你搞错了应该是,`vm.size = {width: this.width, height: this.height}`
  • 谢谢!你节省了我很多时间
【解决方案2】:

您可以使用arrow function (documentation) 来保持覆盖范围:

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

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

【讨论】:

  • 虽然技术上正确,但这行不通,因为他需要两个范围......
  • 我认为当范围已经有this 上下文时使用箭头函数不是一个好习惯
【解决方案3】:

您应该将 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】:

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

这将为您提供函数的范围,或者在您调用它时绑定您的函数,例如

vueMethod("url").bind(this)

【讨论】:

    【解决方案5】:

    因此,当您使用带有关键字 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()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      • 1970-01-01
      • 2021-06-02
      • 2021-10-04
      • 2014-03-13
      相关资源
      最近更新 更多