【问题标题】:Lodash's _.debounce() not working in Vue.jsLodash 的 _.debounce() 在 Vue.js 中不起作用
【发布时间】:2019-04-02 03:06:20
【问题描述】:

当 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();
  },
},

错误:

TypeError: _this2.query 不是函数

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

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

【问题讨论】:

    标签: javascript vue.js lodash


    【解决方案1】:

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

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

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

    【讨论】:

    • 该死!谢谢。我确定我也尝试过这个选项。它有效
    • 效果很好,但 eslint 在 .vue 文件中抱怨“no-invalid-this”。
    • 奇怪,使用这个确切的语法不会触发 this.query() 对我来说
    • 我需要在创建时绑定它才能工作,可能就像@BuddyZ 的问题一样。 data() { return { searchCustomersDebounced: null, },created() { this.debouncedQuery = _.debounce( () => { this.query(); }, 1000 );},
    【解决方案2】:

    我们可以通过简单的 JS (ES6) 用几行代码来完成:

    function update() {
    
        if(typeof window.LIT !== 'undefined') {
            clearTimeout(window.LIT);
        }
    
        window.LIT = setTimeout(() => {
            // do something...
        }, 1000);
    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-28
      • 1970-01-01
      • 2014-08-09
      • 1970-01-01
      • 2019-09-01
      • 2017-05-05
      • 2017-04-02
      • 2021-01-19
      • 2019-11-09
      相关资源
      最近更新 更多