简体   繁体   English

在 Vue 中使用 lodash 油门时传递这个

[英]Passing this when using lodash throttle with Vue

Working from this I have the following code:从这里开始,我有以下代码:

export default {
  data(){
    return {
      width: 0,
      height: 0,
    }
  },
  methods: {
    resizedWindow: _.throttle(this.reset, 200),
    reset(){
      this.width = window.innerWidth;
      this.height = window.innerHeight;
    }
  },
  mounted(){
    this.reset();
    window.addEventListener('resize', this.resizedWindow);
  }
}

But this gives me the following error:但这给了我以下错误:

Uncaught TypeError: Cannot read property 'reset' of undefined未捕获的类型错误:无法读取未定义的属性“重置”

Usually this is to do with this and I (usually) know how to fix that.通常这与this有关,我(通常)知道如何解决这个问题。 You do something like this:你做这样的事情:

// Replace previous resizeWindow with...
resizedWindow(){
  let vm = this;
  _.throttle(vm.reset, 200);
},

But this never fires the reset method.但这永远不会触发reset方法。 I know it must be something silly or gap in my understanding of this – how can I make this work?知道这一定是我this的理解有些愚蠢或差距——我怎样才能做到这一点?

It seems that in your case this is referring to the window object.在您的情况下, this似乎是指window对象。 You can move your resizedWindow method definition to the created hook as seen here to have access to this as the Vue instance ..您可以将resizedWindow方法定义移动到created的钩子,如此处所示,以作为 Vue 实例访问this

export default {
  data(){
    return {
      width: 0,
      height: 0,
    }
  },
  methods: {
    reset(){
      this.width = window.innerWidth;
      this.height = window.innerHeight;
    }
  },
  created() {
    this.resizedWindow = _.throttle(this.reset, 200)
  },
  mounted(){
    this.reset();
    window.addEventListener('resize', this.resizedWindow);
  }
}

Alternatively, you can make use of an IIFE ..或者,您可以使用IIFE ..

export default {
  data(){
    return {
      width: 0,
      height: 0,
    }
  },
  methods: {
    resizedWindow() { (_.throttle(this.reset, 200))() },
    reset(){
      this.width = window.innerWidth;
      this.height = window.innerHeight;
    }
  },
  mounted(){
    this.reset();
    window.addEventListener('resize', this.resizedWindow);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM