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

时间:2018-10-29 08:05:37

标签: javascript vue.js lodash

在修改Vue.js中名为query()的组件属性时,我正在尝试运行名为q的方法。

此操作失败,因为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();
  },
},

错误:

  

TypeError:_this2.query不是函数

如果我按如下方式编写debounce()调用,则TypeError: expected a function错误会在页面加载时更早出现。

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

2 个答案:

答案 0 :(得分:5)

问题来自您在_.debounce中定义的箭头功能的词法范围。 this绑定到您要在其中定义的对象,而不是实例化的Vue实例。

如果您将箭头功能切换为常规功能,则范围已正确绑定:

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

答案 1 :(得分:2)

我们可以用几行代码的普通JS(ES6)来实现:

function update() {

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

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

}

希望这会有所帮助:)

相关问题