防抖函式的相容版本(vue3/vue2/javascript)
// vue 防抖,相容vue3,vue2和普通js
// delay: 延遲時間(毫秒)
1.封裝 debounce.js
export default class Debounce {
constructor(delay){
this.delay = delay ? delay : 500;
this.timeOut = null;
}
debounceEnd(){
return new Promise((resolve,reject)=>{
if(this.timeout){
clearTimeout(this.timeout)
}
this.timeout = setTimeout(()=>{
resolve('success');
},this.delay)
})
}
}
注:不需要把呼叫的函式作為引數傳進去,僅僅通過使用promise來讓我們的程式碼同步化,達到防抖的效果。
在vue3的setup中呼叫。通過new Debounce並傳入一個延遲時間。獲得一個例項,這個例項返回一個promise的成功回撥,
如果當前頁面有多個不同的操作需要防抖,可以通過new多個例項來分別處理。
在vue3中引入debounce.js
setup(){
const de = new Debounce(500);
async function handleInit(){
await de.debounceEnd()
//模擬傳送請求
setTimeout(()=>{
.....
},100)
}
}
在vue2中
created(){
this.de = new Debounce(500)
},
methods:{
async handleClick(name){
await this.de.debounceEnd();
//500毫秒之後列印
}
}
在原生js上
let div = document.querySelector('#div');
const de = new Debounce(1000);
div.addEventListener('click',async()=>{
await de.debounceEnd();
})