vuepress-theme-vdoing/docs/《Vue》笔记/99.其他/80.Vue中的防抖函数封装和使用.md

1.1 KiB
Raw Blame History

title date permalink categories tags author
Vue中的防抖函数封装和使用 2020-02-04 13:10:19 /pages/fb08e252dfd8fdfd
《Vue》笔记
其他
null
name link
xugaoyi https://github.com/xugaoyi

Vue中的防抖函数封装和使用

如搜索框中,每改变一个数值就请求一次搜索接口,当快速的改变数值时并不需要多次请求接口,这就需要一个防抖函数:

// 防抖函数
export function debounce(func, delay) { // func 函数 delay间隔时间
  let timer
  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func.apply(this, args)
    }, delay)
  }
}




//使用:
import { debounce } from '@/common/js/util'

created() {
    /**
     * 为什么不直接在watch里面写
     * 因为要做防抖处理,防止在快速输入时多次请求接口
     */
    this.$watch('query', debounce((newQuery) => {
      this.$emit('query', newQuery)
    }, 200))
  }

相关文章

防抖与节流函数