【问题标题】:Using Vue.js how to you flush a method that is debounced with lodash?使用 Vue.js 如何刷新使用 lodash 去抖动的方法?
【发布时间】:2019-03-29 22:31:34
【问题描述】:

Vue.js 文档建议使用 lodash 的 debounce 函数来消除昂贵的方法,我已经成功实现了。但有时我不想立即采取行动,lodash 的文档说:

debounced 函数带有一个 cancel 方法来取消延迟的 func 调用和一个 flush 方法来立即调用它们

但就是这样。没有关于如何调用 flush 方法的信息。我找到了this 博客文章,但我不确定如何在 Vue.js 组件中实现它。

这就是我目前在我的 Vue.js 组件中拥有的 (codepen):

<template>
  <input type='text' @keyup="change" @keyup.enter="changeNow">
</template>

<script>
export default {
  name: "MyComponent",
  methods: {
    change: _.debounce(function() {
      console.log("changing...");
    }, 250),
    changeNow: function() {
      this.change();
      this.change.flush();
    }
  }
};
</script>

change 被正确地去抖动并且只在键入后运行一次,正如预期的那样。但是,changeNow 会抛出以下错误:

未捕获的类型错误:this.change.flush 不是函数

任何关于如何实现这一点的建议将不胜感激!

【问题讨论】:

    标签: javascript vue.js lodash


    【解决方案1】:

    由于 vue 处理方法部分的方式存在怪癖,您遇到了问题。

    默认情况下,Vue 只需要方法列表中的函数,然后循环遍历这些方法并在它们上调用 .bind 以确保 this 始终有效。

    由于这种循环,您只能访问函数本身,而不能访问这些函数具有的其他成员。

    如果将 change 方法添加到数据部分,则可以访问其属性并调用 flush 方法:

    var app = new Vue({
        el: "#app",    
          data: {
                change: _.debounce(function() {
            console.log("changing...");
          }.bind(this), 1000),
        },
        methods: {
          changeNow: function() {
            this.change.flush();
          }
        }
      });
    

    https://codepen.io/anon/pen/gBZrrj?editors=1111

    【讨论】:

      【解决方案2】:

      如果您将方法定义移动到创建的钩子中,这似乎可以工作,如the docs 中的示例..

      var app = new Vue({
          el: "#app",
          created() {
            this.change = _.debounce(function() {
              console.log("changing...");
            }, 1000);
            this.changeNow = function() {
              console.log("now...")
              this.change();
              this.change.flush();
            };
          }
        });
      

      Codepen

      【讨论】:

        猜你喜欢
        • 2017-07-08
        • 2021-07-16
        • 2017-05-03
        • 2016-07-17
        • 2019-01-21
        • 2019-01-27
        • 2015-12-03
        • 2014-12-27
        • 2015-05-21
        相关资源
        最近更新 更多