uniapp項目使用防抖及節(jié)流的方案實戰(zhàn)
更新時間:2023年01月19日 11:52:28 作者:費玉清
防抖就是指觸發(fā)事件后把觸發(fā)非常頻繁的事件合并成一次去執(zhí)行,節(jié)流是指頻繁觸發(fā)事件時只會在指定的時間段內(nèi)執(zhí)行事件回調(diào),即觸發(fā)事件間隔大于等于指定的時間才會執(zhí)行回調(diào)函數(shù),這篇文章主要給大家介紹了關(guān)于uniapp項目使用防抖及節(jié)流的相關(guān)資料,需要的朋友可以參考下
此方案出現(xiàn)的理由
- 小程序中無法使用vue.directive的指令方法函數(shù)實現(xiàn)防抖節(jié)流
- 傳統(tǒng)的防抖節(jié)流方式相對繁瑣
實現(xiàn)方案及效果
- 新建一個debounce-view組件
- 直接用debounce-view包裹需要防抖的內(nèi)容即可,如下:
<debounce-view @thTap="buyNow"> <view class="buy-now">立即購買</view> </debounce-view>
防抖組件內(nèi)容:
//debounce-view <template> <view @click.stop="deTap"> <slot></slot> </view> </template> <script> function deBounce(fn, delay = 500, immediate) { let timer = null, immediateTimer = null; return function() { let args = arguments, context = this; // 第一次觸發(fā) if (immediate && !immediateTimer) { fn.apply(context, args); //重置首次觸發(fā)標識,否則下個周期執(zhí)行時會受干擾 immediateTimer = setTimeout(() => { immediateTimer = null; }, delay); } // 存在多次執(zhí)行時,重置動作需放在timer中執(zhí)行; if (immediateTimer) clearTimeout(immediateTimer); if (timer) clearTimeout(timer); timer = setTimeout(() => { fn.apply(context, args); timer = null; immediateTimer = null; }, delay); } } export default { methods: { deTap: deBounce(function() { console.log('deTap') this.$emit('deTap') }, 500, true), } } </script> <style> </style>
節(jié)流組件內(nèi)容:
<template> <view @click.stop="thTap"> <slot></slot> </view> </template> <script> // 第二版 function throttle(func, wait) { var timeout; var previous = 0; return function() { context = this; args = arguments; if (!timeout) { timeout = setTimeout(function() { timeout = null; func.apply(context, args) }, wait) } } } export default { methods: { thTap: throttle(function() { this.$emit('thTap') }, 500) } } </script> <style> </style>
總結(jié)
- 上述方法有有點但也有缺點,優(yōu)點是使用起來非常的快捷方便,缺點是時間目前是寫死的,各位看官如果有新的想法或者意見還請指教小弟一二
到此這篇關(guān)于uniapp項目使用防抖及節(jié)流的文章就介紹到這了,更多相關(guān)uniapp使用防抖及節(jié)流內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Javascript中prototype屬性實現(xiàn)給內(nèi)置對象添加新的方法
這篇文章主要介紹了Javascript中prototype屬性實現(xiàn)給內(nèi)置對象添加新的方法,涉及javascript中prototype屬性的使用技巧,需要的朋友可以參考下2015-05-05