防抖与节流(鼠标移入事件每隔一段时间执行)

废话不多说,直接怼代码

<template>
	<div>
		<button @click="show = !show">
			Toggle render
		</button>
		<transition name="custom-classes-transition" enter-active-class="animated tada" leave-active-class="animated bounceOutRight">
			<p v-if="show">hello</p>
		</transition>
		<child></child>
		
		<!-- <div @mousemove="currentFn(1000)" class="num">{{num}}</div> -->
		<div @mousemove="currentJl(1000)" class="num">{{num}}</div>
		
		<div @click="toLink()">跳转</div>
	</div>
</template>

<script>
	import child from './child.vue'; // 引入子组件
	export default {
		name: "father",
		data() {
			return {
				show: true,
				num: 1,
				flag: true,//初次点击触发一次
				timer: null,
				currentTime: 0 //中间时间
			}
		},
		created() {
			this.num = 0;
		},
		methods: {
			doCount(){
				console.log('进入了');
				this.num++;
			},
			currentFn(wiat){ //防抖
				var that = this;
				clearTimeout(that.timer);
				if(that.flag){
					if(!that.timer){ //第一次进入
						that.doCount();
					}
					that.timer = setTimeout(()=>{
						that.timer = null;
					},wiat);	
				}else{					
					that.timer = setTimeout(()=>{
						that.doCount();
					},wiat)
				}				
			},
			currentJl(wiat){ //节流
				var now = + new Date(); //格林威治时间到当前时间的毫秒数
				if(now - this.currentTime > wiat){
					this.doCount();
					this.currentTime = now;
				}
			},
			toLink(){
				this.$router.push({
					path: '/newFile'
				})
			}
		},
		components: {
			child
		}
	}
</script>

<style scoped>
	.fade-enter-active,
	.fade-leave-active {
		animation: bounce-in .5s;
	}

	.fade-enter,
	.fade-leave-to {
		opacity: 0;
	}
	
	.num{
		width: 3rem;
		height: 2rem;
		background-color: #666666;
		color: #FFFFFF;
		text-align: center;
		line-height: 2rem;
	}
</style>

防抖:当持续触发事件时,一定时间内没有再触发事件,事件处理函数才会执行一次,如果设定时间到来之前,又一次触发了时间,就重新开始延时.
节流:当持续触发事件时,保证一定时间段内调用一次事件处理函数.

通俗示例解释:
小明家水管漏水,每隔一秒钟第一滴(节流:只要没有修好,就会每隔一段时间执行)
小明家水管漏水,每打水管一次,三秒后才会再漏水,每打一次就重新计时(防抖:在一段时间间隔内执行,触发是会重新开始计时)

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值