最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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)文章

最新評論

芮城县| 济源市| 西藏| 台江县| 平阳县| 枝江市| 柳州市| 株洲县| 方山县| 高雄县| SHOW| 沙雅县| 淅川县| 环江| 嵩明县| 德江县| 绩溪县| 贞丰县| 安徽省| 那坡县| 政和县| 泸溪县| 横山县| 商城县| 中宁县| 固始县| 泸定县| 军事| 正阳县| 永德县| 广州市| 大城县| 民县| 广河县| 从化市| 安塞县| 阜宁县| 赤壁市| 柘城县| 富顺县| 哈巴河县|