Lodash的_.debounce()在Vue.js中不起作用

xurqigkl  于 2023-02-09  发布在  Vue.js
关注(0)|答案(3)|浏览(636)

当Vue.js中名为q的组件属性被修改时,我尝试运行名为query()的方法。
这会失败,因为this.query()是未定义的。This引用了我的组件的示例,但不知何故并不包含这些方法。
下面是我尝试查看组件属性q并运行query()函数的相关代码部分:

methods: {
  async query() {
    const url = `https://example.com`;
    const results = await axios({
      url,
      method: 'GET',
    });
    this.results = results.items;
  },
  debouncedQuery: _.debounce(() => { this.query(); }, 300),
},
watch: {
  q() {
    this.debouncedQuery();
  },
},

错误:
类型错误:_this2.query不是函数
如果我按照下面的方式编写debounce()调用,TypeError: expected a function错误甚至会出现得更早,在页面加载时。

debouncedQuery: _.debounce(this.query, 300),
izj3ouym

izj3ouym1#

问题来自于您在_.debounce中定义的arrow函数的词法范围。this绑定到您在其中定义它的对象,而不是示例化的Vue示例。
如果将arrow函数切换为常规函数,则作用域的绑定正确:

methods: {
  // ...
  debouncedQuery: _.debounce(function () { this.query(); }, 300)
}
nbysray5

nbysray52#

我们可以通过简单的JS(ES6)实现,只需几行代码:

function update() {

    if(typeof window.LIT !== 'undefined') {
        clearTimeout(window.LIT);
    }

    window.LIT = setTimeout(() => {
        // do something...
    }, 1000);

}
vmjh9lq9

vmjh9lq93#

正如在另一篇文章中所回答的,这在Vue中是未定义的,使用去抖动方法添加去抖动IMO的最好方法是在方法中创建方法,例如:

setHover() {
      if (this.hoverStatus === 'entered') {
        this.hoverStatus = 'active'
      }
    },

但是,然后将其替换在您创建的块中,例如:

created() {
    this.setHover = debounce(this.setHover, 250)
  },

相关问题