VueJs way to implement debounce click

Well, I assume that you don't need me to explain what is debounce or something like this. And assume you using the lodash library. If you are looking for an explanation then this article is not for you.


I found that could have multiple ways to implemented this . Each method has pros and cons, but I don't know which one has the best performance.👻

Vuejs is good, but it still lacks customize features like modifiers. I cannot found any example of a custom modifier for the @click, it only has the once/prevent/passive, etc..... I would like a modifier to prevent it from executing multiple times of clicking.


After study about the debouncing, there are multiple ways. All using lodash as 


1) Directly put before the function in front of the function like the example below.

methods: {

clickHandler: _.debounce(function(e) { // implementation of the function }, 400)

}

2) Put in Directive, after many testing it finally work and have some limitations.


const debounce = {

  bind (el, binding, vnode) {

    el.debounceMethod = _.debounce(binding.value, 800)

    el.addEventListener(binding.arg, el.debounceMethod)

  },

  unbind (el, binding) {

    el.removeEventListener(binding.arg, el.debounceMethod)

  }

}


First put the first section into the directive.js,

then you can put following code it in the vue main.js file

Vue.directive('debounce', directiveMethod.debounce)


then it will become the global in the app you could just use the following method like the below.

<button v-debounce:click="testing" >testing</button> 



Hope can help you all thanks.



Comments

Popular posts from this blog

Reading and Writing Operation of SRAM

Transmission Control Protocol (TCP)

File transfer from android to linux