Javascript 在Vue中使用lodash油门时通过此选项

Javascript 在Vue中使用lodash油门时通过此选项,javascript,vue.js,this,lodash,Javascript,Vue.js,This,Lodash,我有以下代码: export default { data(){ return { width: 0, height: 0, } }, methods: { resizedWindow: _.throttle(this.reset, 200), reset(){ this.width = window.innerWidth; this.height = window.innerHeight; }

我有以下代码:

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);
  }
}
但这给了我以下错误:

未捕获的TypeError:无法读取未定义的属性“reset”

通常这与
这个
有关,我(通常)知道如何解决这个问题。你可以这样做:

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

但这不会触发
reset
方法。我知道这一定是我对
这件事的理解有点愚蠢或差距-我如何才能使这件事起作用?

在你的情况下
这件事似乎是指
窗口
对象。您可以将
resizedWindow
方法定义移动到创建的
钩子中,以作为Vue实例访问

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);
  }
}
或者,您可以使用
iLife

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);
  }
}
“this”是未定义的,因为
\u0.throttle(this.reset,200)
甚至在“exports”赋值之前就调用对象定义,所以“this”的引用是窗口(或者在您的情况下是未定义的,因为您启用了严格模式)。