vue2/3 防抖

发布时间 2023-10-13 14:58:34作者: Chaplink
//vue2 optionsAPI
data:{
	timeout:null
},
methods:{
	debounceFn(val){
	 if(this.timeout !== null){
	 	clearTimeout(this.timeout);
	}
	this.timeout  = setTimeout(() => {
		console.log(val)
	},200)
}
//vue3 compositionAPI
const debounce = (fn, wait) {
    let timeout = null
    return function () {
        if (timeout) {
            clearTimeout(timeout)
        }
        timeout = setTimeout(() => fn(), wait)
    }
}
const debounceFn = debounce((val) => {
        console.log(val)
}, 200)