Vue中使用防抖和节流

文章目录

防抖

防抖:触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间
应用场景: 登陆,发短信(倒计时),提交请求等,主要是为了防止用户点击过快。

在vue中为了方便管理,在utils文件夹下面新建一个公共方法Debounce.js(名字随便起)

在这里插入图片描述

Debounce.js的代码

export default function(fn, delay = 1000) {
    let timer
    return function(...args) {
        clearInterval(timer)
        timer = setTimeout(() => {
            fn.call(this, ...args)
        }, delay)
    }
}

在需要的页面中用Import引入
vue页面代码

<template>
  <div class="about">
    <button @click="clickeMe">点击我</button>
  </div>
</template>
<script>
import debounce from "@/utils/Debounce"
export default {
  name: 'Home',
  components: {
  },
  methods:{
      clickeMe: debounce(function (){ 
         console.log("我被点击了")  //这里写需要的代码 
      },500) 
  }
}
</script>
vue3写法
<script setup>
import debounce from "@/utils/Debounce"   
const clickeMe = debounce(async() => {
  console.log( "await我被点击了");//这里写需要的代码 
},1000); 

</script>

最后看效果截图
在这里插入图片描述
效果如图点击了五次只执行了一次~~

节流

节流:高频事件触发,但在n秒内只会执行一次。
应用场景: 滚动条滚动、拖拽、mousedown、keydown事件等。
声明

function throttle(handler, wait) {
    let lastTime = 0; // 上一次触发的时间,第一次默认为0
    return function () {
        let newTime = Date.now() // 新的触发时的时间
        if (newTime - lastTime > wait) {
            handler.apply(this, arguments);
            lastTime = newTime; // 更新上一次触发的时间
        }
    }
}

export default throttle

引用

import throttle from "@/utils/Throttle";

methods:{
 move: throttle(function(val){
    //逻辑
 },1000)
}

请添加图片描述
每天学习一点进步一点,加油!!!

  • 9
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jet_closer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值