目录

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

# 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))
  }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

# 相关文章

防抖与节流函数 (opens new window)

上次更新: 2023/07/11, 15:43:07
最近更新
01
基本知识
07-18
02
卷积神经网络识别图像
07-18
03
损失函数
07-18
更多文章>