Search code examples
javascriptvue.jslodash

Lodash _.debounce doesn't work in VueJS event


I'm trying to use debounce in my filter. I don't want to send a request on every input text change, I'd rather wait let's say one second.

The problem is that the filter seems not to be called at all if I use _.debounce.

  <div class="md-form">
        <i class="fas fa-search prefix"></i>
        <input type="text" class="form-control" v-model="filter.fulltext" @input="runFilter" id="x">
        <label for="x">Fulltext vyhľadávanie</label>
  </div>

var app = new Vue({
        delimiters: ['[[', ']]'],
        el: '#app',
        data: { ....
        methods:{
            runFilter() {
                var self = this;

                _.debounce(function () {
                    self.records_page = 1;
                    self.loadRecords();
                    self.loadMarkers();
                 }, 1000)

               },
               ....

Do you know why it isn't called after one second?


Solution

  • The _.debounce() return a function with closure, so you have to find a place to store the debounced function. Usually, you can debounce the function and put the debounced function on this in the created hook.

    created() {
       this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
    }
    

    Just like this how it does in the official document. https://v2.vuejs.org/v2/guide/computed.html