How to implement debounce in Vue2?

前端 未结 13 681
梦谈多话
梦谈多话 2020-11-27 11:08

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



        
13条回答
  •  庸人自扰
    2020-11-27 11:22

    updated in 2020

    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

    
    

    Codepen


    Option 2: In-component, also no deps

    (Recommended if using once or in small project)

    Component.vue

    
    
    
    

    Codepen

提交回复
热议问题