【问题标题】:Passing this when using lodash throttle with Vue在 Vue 中使用 lodash 油门时传递这个
【发布时间】:2018-10-19 08:39:03
【问题描述】:

Working from this我有以下代码:

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 有关,我(通常)知道如何解决这个问题。你可以这样做:

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

但这永远不会触发reset 方法。我知道这一定是我对this的理解有些愚蠢或差距——我怎样才能做到这一点?

【问题讨论】:

  • "this" 是未定义的,因为_.throttle(this.reset, 200) 甚至在“exports”分配之前就调用对象定义,因此“this”的引用是窗口(或在您的情况下为“未定义”,因为您有严格模式启用)。

标签: javascript vue.js this lodash


【解决方案1】:

在您的情况下,this 似乎指的是window 对象。您可以将 resizedWindow 方法定义移动到 created 挂钩 as seen here 以访问 this 作为 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);
  }
}

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

【讨论】:

    猜你喜欢
    • 2022-08-11
    • 2020-12-05
    • 2019-11-29
    • 2019-05-22
    • 2021-07-15
    • 2020-02-13
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多