vuejs .vue组件debounce将自己作为输入

时间:2016-12-12 11:29:26

标签: vuejs2

在我开始使用.vue组件之前,我编写了一个组件,其中包含以下代码,可以成功运行

import { debounce } from '../utils/debounce';
Vue.component('play-list-manager', {
  ...
  methods: {
    renamePlayList: debounce((oldName, event) => {
      store.dispatch(Actions.renamePlayList(oldName, event.target.value));
      }, 500),
  },
  template: `<input
            type="text"
            v-bind:value="tag.name"
            v-on:keyup="renamePlayList(tag.name, $event)"
            placeholder="... playlist name">`
});

但是当我切换到.vue组件时,它不再起作用了

问题是去抖动的输入不是('some name', Event),而是现在是(function(oldName, event), 500)。所以它将debounce的输入作为输入。

添加去抖功能的正确方法是什么。

完成这里是我的辩护功能

export function debounce(func, wait) {
    // we need to save these in the closure
    let timeout;
    let args;
    let context;
    let timestamp;

    return () => {
        // save details of latest call
        context = this;
        args = [].slice.call(arguments, 0);
        timestamp = new Date();

        // this is where the magic happens
        const later = () => {
            // how long ago was the last call
            const last = (new Date()) - timestamp;

            // if the latest call was less that the wait period ago
            // then we reset the timeout to wait for the difference
            if (last < wait) {
                timeout = setTimeout(later, wait - last);

                // or if not we can null out the timer and run the latest
            } else {
                timeout = null;
                func.apply(context, args);
            }
        };

        // we only need to set the timer now if one isn't already running
        if (!timeout) {
            timeout = setTimeout(later, wait);
        }
    };
}

1 个答案:

答案 0 :(得分:1)

我找到了解决方案,但我完全不理解

export function debounce(func, wait) {
    // we need to save these in the closure
    let timeout;
    let args;
    let context;
    let timestamp;

    return function() {
        // save details of latest call
        context = this;
        args = [].slice.call(arguments, 0);
        timestamp = new Date();

        // this is where the magic happens
        const later = () => {
            // how long ago was the last call
            const last = (new Date()) - timestamp;

            // if the latest call was less that the wait period ago
            // then we reset the timeout to wait for the difference
            if (last < wait) {
                timeout = setTimeout(later, wait - last);

                // or if not we can null out the timer and run the latest
            } else {
                timeout = null;
                func.apply(context, args);
            }
        };

        // we only need to set the timer now if one isn't already running
        if (!timeout) {
            timeout = setTimeout(later, wait);
        }
    };
}
相关问题