在vue中输入框如何实现防抖

问题遇到的现象和发生背景

就是用户在输入框输入时需要向后台请求关键字信息并展示,需要用到防抖函数

首先新建一个js文件

// 防抖函数
export function debounce (fn, delay) {
  // 记录上一次的延时器
  var timer = null
  delay = delay || 300
  return function () {
    var args = arguments
    var that = this
    // 清除上一次延时器
    clearTimeout(timer)
    timer = setTimeout(function () {
      fn.apply(that, args)
    }, delay)
  }
}

在页面中引用

img

img


 export default {
        name: "",
        data() {
            answer: "",
            timeout: null
        },
        method: {
            change() {
                if(this.timeout){
                    clearTimeout(this.timeout)
                }
                this.timeout = setTimeout(() => {
                    console.log(this.answer)
                }, 500);
            }
        }
    }