Are Vue.js and debounce (lodash/underscore) compatible? Are Vue.js and debounce (lodash/underscore) compatible? vue.js vue.js

Are Vue.js and debounce (lodash/underscore) compatible?


Here's an improved version of @saurabh's version.

var app = new Vue({  el: '#root',  data: {    message: '',    messageLen: 0  },  methods: {    updateLen: _.debounce(      function() {        this.messageLen = this.message.length      }, 300)          }})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.js"></script><script src="https://unpkg.com/underscore@1.8.3"></script> <!-- undescore import --><div id="root">  <input v-model="message" v-on:keyup="updateLen">Length: <span>{{ messageLen }}</span></div>


Why this is happening is because Vue invokes methods only when vue variables used in the methods changes, if there are no changes in the vue varaibles, it will not trigger those methods.

In this case as well, once we stop typing, it will continue to show last called method's output and will only show again once you enter the input again.

One alternate approach if you dont want to call an function on all inputs, you can call a mehtod on blur event, so method will be invoked only when focus goes out of input field, like following:

var app = new Vue({  el: '#root',  data: {    message: '',    messageLen: 0  },  methods: {    updatateLen:      function() {        this.messageLen = this.message.length      }          }})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.js"></script><script src="https://unpkg.com/underscore@1.8.3"></script> <!-- undescore import --><div id="root">  <input v-model="message" v-on:blur="updatateLen">Length: <span>{{ messageLen }}</span></div>