使用方法

  1. 在公共方法中(如 utils.js 中),加入函数防抖和节流方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 防抖方法
export const debounce = (f, wait = 500) => {
    let timer
return (...args) => {
clearTimeout(timer)
timer = setTimeout(() => {
f(...args)
}, wait)
}
}
// 节流
export const throttle = (f, wait = 500) => {
let timer
return (...args) => {
if (timer) { return }
timer = setTimeout(() => {
f(...args)
timer = null
}, wait)
}
}
  1. 在需要使用的组件引用
1
2
3
4
// 文本搜索
<input placeholder="搜索你想要的内容" @input="onInput" :value="kw"/>

import { debounce } from "../../common/utils"
  1. 在 methods 中使用
1
2
3
4
5
6
7
8
9
10
11
...
methods: {
onInput({target}){
        this.debounceSearch(this, target.value)
    },
    debounceSearchdebounce((that, kw) => {
        that.kw = kw
        that.faqIndex("search")
    })
}
...

总结简要

防抖:防止抖动,单位时间内事件触发会被重置,避免事件被误伤触发多次。代码实现重在清零 clearTimeout,使用场景(发送短信、调整浏览器窗口、文本编辑器保存)
节流:控制流量,单位时间内事件只能触发一次,如果服务器端的限流即 Rate Limit。代码实现重在开锁关锁 timer=timeout; timer=null使用场景。(onresize/mousemove/onscroll事件,下拉搜索框)