uniapp項(xiàng)目使用防抖及節(jié)流的方案實(shí)戰(zhàn)
更新時(shí)間:2023年01月19日 11:52:28 作者:費(fèi)玉清
防抖就是指觸發(fā)事件后把觸發(fā)非常頻繁的事件合并成一次去執(zhí)行,節(jié)流是指頻繁觸發(fā)事件時(shí)只會(huì)在指定的時(shí)間段內(nèi)執(zhí)行事件回調(diào),即觸發(fā)事件間隔大于等于指定的時(shí)間才會(huì)執(zhí)行回調(diào)函數(shù),這篇文章主要給大家介紹了關(guān)于uniapp項(xiàng)目使用防抖及節(jié)流的相關(guān)資料,需要的朋友可以參考下
此方案出現(xiàn)的理由
- 小程序中無法使用vue.directive的指令方法函數(shù)實(shí)現(xiàn)防抖節(jié)流
- 傳統(tǒng)的防抖節(jié)流方式相對(duì)繁瑣
實(shí)現(xiàn)方案及效果
- 新建一個(gè)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ā)標(biāo)識(shí),否則下個(gè)周期執(zhí)行時(shí)會(huì)受干擾
immediateTimer = setTimeout(() => {
immediateTimer = null;
}, delay);
}
// 存在多次執(zhí)行時(shí),重置動(dòng)作需放在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é)
- 上述方法有有點(diǎn)但也有缺點(diǎn),優(yōu)點(diǎn)是使用起來非常的快捷方便,缺點(diǎn)是時(shí)間目前是寫死的,各位看官如果有新的想法或者意見還請(qǐng)指教小弟一二
到此這篇關(guān)于uniapp項(xiàng)目使用防抖及節(jié)流的文章就介紹到這了,更多相關(guān)uniapp使用防抖及節(jié)流內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
BootStrap Table對(duì)前臺(tái)頁面表格的支持實(shí)例講解
bootstrap-table是在bootstrap的基礎(chǔ)上面做了一些封裝,所以在使用bootstrap-table之前要導(dǎo)入的js和css,下面通過本文給大家詳細(xì)介紹需要引入的文件,對(duì)bootstrap table 表格感興趣的朋友一起看看吧2016-12-12
JS 實(shí)現(xiàn)緩存算法的示例(FIFO/LRU)
這篇文章主要介紹了JS 實(shí)現(xiàn)緩存算法的示例(FIFO/LRU),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-03-03
Javascript中prototype屬性實(shí)現(xiàn)給內(nèi)置對(duì)象添加新的方法
這篇文章主要介紹了Javascript中prototype屬性實(shí)現(xiàn)給內(nèi)置對(duì)象添加新的方法,涉及javascript中prototype屬性的使用技巧,需要的朋友可以參考下2015-05-05
Javascript筆記一 js以及json基礎(chǔ)使用說明
JavaScript中的數(shù)據(jù)很簡潔的。簡單數(shù)據(jù)只有 undefined, null, boolean, number和string這五種,而復(fù)雜數(shù)據(jù)只有一種,即object。2010-05-05

