防抖在vue中应用
防抖(Debouncing)
定义:在一段时间内只执行一次函数,常用于用户停止操作后才执行的场景。
应用:适用于搜索输入框、窗口调整、搜索按钮等场景,避免频繁触发事件处理函
以下伪代码…
const debouncedGetEntries: null
activated:{ debouncedGetEntries = this.createDebounce(this.getEntries, 300) }
const createDebounce(func, wait = 500) {let timer = nullconst that = this// 防抖函数本体const debounced = function (...args) {const context = that // 保存当前组件实例的 thisclearTimeout(timer) // 清除上一次未执行的定时器timer = setTimeout(() => {func.apply(context, args) // 绑定组件实例的 this 并执行}, wait)}// 清理定时器的方法(用于组件卸载时调用)debounced.cancel = () => {clearTimeout(timer)timer = null}return debounced},