亲宝软件园·资讯

展开

uniapp项目使用防抖及节流的方案实战

费玉清 人气:0

此方案出现的理由

实现方案及效果

<debounce-view @thTap="buyNow">
        <view class="buy-now">立即购买</view>
</debounce-view>

防抖组件内容:

//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;

			// 第一次触发
			if (immediate && !immediateTimer) {

				fn.apply(context, args);
				//重置首次触发标识,否则下个周期执行时会受干扰
				immediateTimer = setTimeout(() => {
					immediateTimer = null;
				}, delay);
			}
			// 存在多次执行时,重置动作需放在timer中执行;
			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>

节流组件内容:

<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>

总结

加载全部内容

相关教程
猜你喜欢
用户评论