ChatGPT解决这个技术问题 Extra ChatGPT

How to implement debounce in Vue2?

I have a simple input box in a Vue template and I would like to use debounce more or less like this:

<input type="text" v-model="filterKey" debounce="500">

However the debounce property has been deprecated in Vue 2. The recommendation only says: "use v-on:input + 3rd party debounce function".

How do you correctly implement it?

I've tried to implement it using lodash, v-on:input and v-model, but I am wondering if it is possible to do without the extra variable.

In template:

<input type="text" v-on:input="debounceInput" v-model="searchInput">

In script:

data: function () {
  return {
    searchInput: '',
    filterKey: ''
  }
},

methods: {
  debounceInput: _.debounce(function () {
    this.filterKey = this.searchInput;
  }, 500)
}

The filterkey is then used later in computed props.

I would suggest to carefully read: vuejs.org/v2/guide/…
There is an example in the guide: vuejs.org/v2/guide/computed.html#Watchers

k
kissu

I am using debounce NPM package and implemented like this:

<input @input="debounceInput">
methods: {
    debounceInput: debounce(function (e) {
      this.$store.dispatch('updateInput', e.target.value)
    }, config.debouncers.default)
}

Using lodash and the example in the question, the implementation looks like this:

<input v-on:input="debounceInput">
methods: {
  debounceInput: _.debounce(function (e) {
    this.filterKey = e.target.value;
  }, 500)
}

Thanks for this. I found a similar example in some other Vue docs: vuejs.org/v2/examples/index.html (the markdown editor)
Proposed solution has a problem when there are several component instances on the page. Problem is described and solution presented here: forum.vuejs.org/t/issues-with-vuejs-component-and-debounce/7224/…
e.currentTarget is overwritten to null this way
Would recommend to add a v-model=your_input_variable to the input and in your vue data. So you do not rely on e.target but use Vue so you can access this.your_input_variable instead of e.target.value
For those using ES6, it's important to emphasize the use of the anonymous function here: if you use an arrow function you will not be able to access this within the function.
k
kissu

Option 1: Re-usable, no deps

- Recommended if needed more than once in your project

/helpers.js

export function debounce (fn, delay) {
  var timeoutID = null
  return function () {
    clearTimeout(timeoutID)
    var args = arguments
    var that = this
    timeoutID = setTimeout(function () {
      fn.apply(that, args)
    }, delay)
  }
}

/Component.vue

<script>
  import {debounce} from './helpers'

  export default {
    data () {
      return {
        input: '',
        debouncedInput: ''
      }
    },
    watch: {
      input: debounce(function (newVal) {
        this.debouncedInput = newVal
      }, 500)
    }
  }
</script>

Codepen

Option 2: In-component, also no deps

- Recommended if using once or in small project

/Component.vue

<template>
    <input type="text" v-model="input" />
</template>

<script>
  export default {
    data: {
        timeout: null,
        debouncedInput: ''
    },
    computed: {
     input: {
        get() {
          return this.debouncedInput
        },
        set(val) {
          if (this.timeout) clearTimeout(this.timeout)
          this.timeout = setTimeout(() => {
            this.debouncedInput = val
          }, 300)
        }
      }
    }
  }
</script>

Codepen


I prefer this option because I probably don't need an npm package for 11 lines of code....
This should be the marked answer, this works really well and takes nearly no space at all. Thanks!
hi, possible add a TypeScript Version o helper?
is any one else getting a jest error when implementing the first option? [Vue warn]: Error in callback for watcher "input": "TypeError: Cannot read property 'call' of undefined"
k
kissu

Assigning debounce in methods can be trouble. So instead of this:

// Bad
methods: {
  foo: _.debounce(function(){}, 1000)
}

You may try:

// Good
created () {
  this.foo = _.debounce(function(){}, 1000);
}

It becomes an issue if you have multiple instances of a component - similar to the way data should be a function that returns an object. Each instance needs its own debounce function if they are supposed to act independently.

Here's an example of the problem:

Vue.component('counter', { template: '

{{ i }}
', data: function(){ return { i: 0 }; }, methods: { // DON'T DO THIS increment: _.debounce(function(){ this.i += 1; }, 1000) } }); new Vue({ el: '#app', mounted () { this.$refs.counter1.increment(); this.$refs.counter2.increment(); } });
Both should change from 0 to 1:


Could you explain why assigning debounce in methods can be trouble?
See Example links are prone to link-rot. It's better to explain the problem in the answer - it will make it more valuable for the readers.
Thank you very match, i had a bad time trying to understand why the data displayed on the console was right but not applied on the app ...
just add it to your data() then.
@Hybridwebdev I reckon he got it from Linus Borg's answer from the Vue forum, so I would say that this is the correct solution forum.vuejs.org/t/…
k
kissu

Very simple without lodash

handleScroll: function() {
  if (this.timeout) 
    clearTimeout(this.timeout); 

  this.timeout = setTimeout(() => {
    // your action
  }, 200); // delay
}

As much as I love lodash, this is clearly the best answer for a trailing debounce. Easiest to implement as well as understand.
also is a good thing to add destroyed() { clearInterval(this.timeout) } in order to not having a timeout after destroyed.
Out of all the solutions this is the only one that worked reliably.
Simple, efficient, great !
i am not sure how to use this when text changes on an input field. Can someone show an example?
k
kissu

I had the same problem and here is a solution that works without plugins.

Since <input v-model="xxxx"> is exactly the same as

<input
   v-bind:value="xxxx"
   v-on:input="xxxx = $event.target.value"
>

(source)

I figured I could set a debounce function on the assigning of xxxx in xxxx = $event.target.value

like this

<input
   v-bind:value="xxxx"
   v-on:input="debounceSearch($event.target.value)"
>

methods:

debounceSearch(val){
  if(search_timeout) clearTimeout(search_timeout);
  var that=this;
  search_timeout = setTimeout(function() {
    that.xxxx = val; 
  }, 400);
},

if your input field also had an @input="update_something" action then call this after that.xxx = val that.update_something();
in my methods section I used a slightly different syntax which worked for me: debounceSearch: function(val) { if (this.search_timeout) clearTimeout(this.search_timeout); var that=this; this.search_timeout = setTimeout(function() { that.thread_count = val; that.update_something(); }, 500); },
This is ok if you're having one or very few instances where you need to debounce input. However, you'll quickly realize you'll need to move this to a library or similar if the app grows and this functionality is needed elsewhere. Keep your code DRY.
k
kissu

If you need a very minimalistic approach to this, I made one (originally forked from vuejs-tips to also support IE) which is available here: https://www.npmjs.com/package/v-debounce

Usage:

<input v-model.lazy="term" v-debounce="delay" placeholder="Search for something" />

Then in your component:

<script>
export default {
  name: 'example',
  data () {
    return {
      delay: 1000,
      term: '',
    }
  },
  watch: {
    term () {
      // Do something with search term after it debounced
      console.log(`Search term changed to ${this.term}`)
    }
  },
  directives: {
    debounce
  }
}
</script>

Probably this one should be the accepted solution, with 100+ vote-ups. The OP asked for a compact solution like this, and it nicely decouples the debounce logic.
It will be so hard if you play with array, because this way is depends with the static data
t
tony19

Please note that I posted this answer before the accepted answer. It's not correct. It's just a step forward from the solution in the question. I have edited the accepted question to show both the author's implementation and the final implementation I had used.

Based on comments and the linked migration document, I've made a few changes to the code:

In template:

<input type="text" v-on:input="debounceInput" v-model="searchInput">

In script:

watch: {
  searchInput: function () {
    this.debounceInput();
  }
},

And the method that sets the filter key stays the same:

methods: {
  debounceInput: _.debounce(function () {
    this.filterKey = this.searchInput;
  }, 500)
}

This looks like there is one less call (just the v-model, and not the v-on:input).


Wouldn't this call debounceInput() twice for each change? v-on: will detect the input changes and call debounce, AND because the model is bound, searchInput's watch function will ALSO call debounceInput... right?
@mix3d Do not consider this answer. It was just my investigation I did not want to put in the question. You are most likely right. Check the accepted answer. It's correct and I edited it to match the question.
My mistake... I didn't realize you had answered your own question, ha!
k
kissu

In case you need to apply a dynamic delay with the lodash's debounce function:

props: {
  delay: String
},

data: () => ({
  search: null
}),

created () {
     this.valueChanged = debounce(function (event) {
      // Here you have access to `this`
      this.makeAPIrequest(event.target.value)
    }.bind(this), this.delay)

},

methods: {
  makeAPIrequest (newVal) {
    // ...
  }
}

And the template:

<template>
  //...

   <input type="text" v-model="search" @input="valueChanged" />

  //...
</template>

NOTE: in the example above I made an example of search input which can call the API with a custom delay which is provided in props


u
undefinederror

Although pretty much all answers here are already correct, if anyone is in search of a quick solution I have a directive for this. https://www.npmjs.com/package/vue-lazy-input

It applies to @input and v-model, supports custom components and DOM elements, debounce and throttle.

Vue.use(VueLazyInput) new Vue({ el: '#app', data() { return { val: 42 } }, methods:{ onLazyInput(e){ console.log(e.target.value) } } })

{{val}}


C
CyberAP

To create debounced methods you can use computeds, that way they won't be shared across multiple instances of your component:

<template>
  <input @input="handleInputDebounced">
<template>

<script>
import debounce from 'lodash.debouce';

export default {
  props: {
    timeout: {
      type: Number,
      default: 200,
    },
  },
  methods: {
    handleInput(event) {
      // input handling logic
    },
  },
  computed: {
    handleInputDebounced() {
      return debounce(this.handleInput, this.timeout);
    },
  },
}
</script>

You can make it work with uncontrolled v-model as well:

<template>
  <input v-model="debouncedModel">
<template>

<script>
import debounce from 'lodash.debouce';

export default {
  props: {
    value: String,
    timeout: {
      type: Number,
      default: 200,
    },
  },
  methods: {
    updateValue(value) {
      this.$emit('input', value);
    },
  },
  computed: {
    updateValueDebounced() {
      return debounce(this.updateValue, this.timeout);
    },
    debouncedModel: {
      get() { return this.value; },
      set(value) { this.updateValueDebounced(value); }
    },
  },
}
</script>

A
Amir Khadem

If you are using Vue you can also use v.model.lazy instead of debounce but remember v.model.lazy will not always work as Vue limits it for custom components.

For custom components you should use :value along with @change.native

<b-input :value="data" @change.native="data = $event.target.value" ></b-input>


d
devzom

1 Short version using arrow function, with default delay value

file: debounce.js in ex: ( import debounce from '../../utils/debounce' )

export default function (callback, delay=300) {
    let timeout = null
    return (...args) => {
        clearTimeout(timeout)
        const context = this
        timeout = setTimeout(() => callback.apply(context, args), delay)
    }
}

2 Mixin option

file: debounceMixin.js

export default {
  methods: {
    debounce(func, delay=300) {
      let debounceTimer;
      return function() {
       // console.log("debouncing call..");
        const context = this;
        const args = arguments;
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => func.apply(context, args), delay);
        // console.log("..done");
      };
    }
  }
};

Use in vueComponent:

<script>
  import debounceMixin from "../mixins/debounceMixin";
  export default {
   mixins: [debounceMixin],
        data() {
            return {
                isUserIdValid: false,
            };
        },
        mounted() {
        this.isUserIdValid = this.debounce(this.checkUserIdValid, 1000);
        },
    methods: {
        isUserIdValid(id){
        // logic
        }
  }
</script>

another option, example

Vue search input debounce


F
Fritz

I was able to use debounce with very little implementation.

I am using Vue 2.6.14 with boostrap-vue:

Add this pkg to your package.json: https://www.npmjs.com/package/debounce

Add this to main.js:

import { debounce } from "debounce";
Vue.use(debounce);

In my component I have this input:

          <b-form-input
            debounce="600"
            @update="search()"
            trim
            id="username"
            v-model="form.userName"
            type="text"
            placeholder="Enter username"
            required
          >
          </b-form-input>

All it does is call the search() method and the search method uses the form.userName for perform the search.


v
vlio20

If you could move the execution of the debounce function into some class method you could use a decorator from the utils-decorators lib (npm install --save utils-decorators):

import {debounce} from 'utils-decorators';

class SomeService {

  @debounce(500)
  getData(params) {
  }
}

M
Mayxxp
 public debChannel = debounce((key) => this.remoteMethodChannelName(key), 200)

vue-property-decorator


Could you please add more information about this solution?
Please elaborate a little bit more. Also, note that this is an old thread with well established answers, so can you clarify how your solution is more appropriate for the problem?
It helps more if you supply an explanation why this is the preferred solution and explain how it works. We want to educate, not just provide code.

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now