- 防抖函数应用场景:
- 搜索框搜索输入, 只需要用户最后一次输入完再发送请求
- 手机号、邮箱格式的输入验证检测
- 窗口大小的 resize, 只需窗口调整完成后,计算窗口的大小,防止重复渲染
如何在vue中使用防抖函数
1.在utils文件中新建debounce.js,内容如下:
export function debounce (fn, timerDelay = 1000, immediate) {
let timer
return function () {
const that = this
const args = arguments
if (timer) clearTimeout(timer)
if (immediate) {
const callNow = !timer
timer = setTimeout(() => {
timer = null
}, timerDelay)
if (callNow) fn.apply(that, args)
} else {
timer = setTimeout(function () {
fn.apply(that, args)
}, timerDelay)
}
}
}
2.在组件中引入防抖函数
import { debounce } from '@/utils/debounce'
3.在methods中使用防抖函数
inputSearch: debounce(function () {
this.getListData()
})