相关推荐recommended
uniapp实现事件级防抖
作者:mmseoamin日期:2024-04-30

背景:

uniapp项目中所有页面跳转都会触发多次点击事件,导致页面排版错乱或其他问题

在utils文件夹下创建debounce.js文件

export const Debounce = (fn, wait) => {
	let delay = wait || 500
	let timer
	return function() {
		let args = arguments;
		if (timer) {
			clearTimeout(timer)
		}
		let callNow = !timer
		timer = setTimeout(() => {
			timer = null
		}, delay)
		if (callNow) fn.apply(this, args)
	}
}

使用方式

在需要使用防抖页面引入方法

import { Debounce } from "@/utils/debounce.js";

页面使用

// 原方法
methodName(type) {
	console.log(type)
}
// 修改后方法
methodName: Debounce(function(type) {
	// 逻辑代码
	console.log(type)
}, 1000),

注意: 不要使用箭头函数 () => {}, 会导致this获取不到

如果有更合理或者更好的防抖方法,希望可以多多指教