Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs 2: debounce not working on a watch option

When I debounce this function in VueJs it works fine if I provide the number of milliseconds as a primitive. However, if I provide it as a reference to a prop, it ignores it.

Here's the abbreviated version of the props:

props : {
    debounce : {
        type : Number,
        default : 500
    }
}

Here is the watch option that does NOT work:

watch : {
    term : _.debounce(function () {
        console.log('Debounced term: ' + this.term);
    }, this.debounce)
}

Here is a watch option that DOES work:

watch : {
    term : _.debounce(function () {
        console.log('Debounced term: ' + this.term);
    }, 500)
}

It suspect that it is a scope issue but I don't know how to fix it. If I replace the watch method as follows...:

watch : {
    term : function () {
        console.log(this.debounce);
    }
}

... I get the correct debounce value (500) appearing in the console.

like image 262
DatsunBing Avatar asked Jan 30 '23 06:01

DatsunBing


1 Answers

Another variation to @Bert's answer is to build the watcher's function in created(),

// SO: Vuejs 2: debounce not working on a watch option

console.clear()

Vue.component("debounce",{
  props : {
    debounce : {
      type : Number,
      default : 500
    }
  },
  template:`
    <div>
      <input type="text" v-model="term">
    </div>
  `,
  data(){
    return {
      term: "",
      debounceFn: null
    }
  },
  created() {
    this.debounceFn = _.debounce( () => {
      console.log('Debounced term: ' + this.term);
    }, this.debounce)
  },
  watch : {
    term : function () {
      this.debounceFn();
    }
  },
})

new Vue({
  el: "#app"
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<div id="app">
  <debounce :debounce="2000"></debounce>
</div>

Example on CodePen

like image 102
Richard Matsen Avatar answered Feb 03 '23 08:02

Richard Matsen