VUE3+TS封装防抖和节流函数

防抖

debounce.ts

export function debounce(func: () => void, delay: number) {
    let timer: number;
    return function (this: any, ...args: any[]) {
      clearTimeout(timer);
      timer = window.setTimeout(() => {
        func.apply(this, args);
      }, delay);
    };
  }
  

使用

<template>
    <button ref="submitButton">GET</button>
  </template>
  
  <script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { debounce } from '../utils/debounce'; // 导入防抖函数
  
  // 使用 ref 访问 DOM 元素
  const submitButton = ref<HTMLElement | null>(null);
  
  onMounted(() => {
    if (submitButton.value) {
      submitButton.value.addEventListener(
        'click',
        debounce(() => {
          console.log('clicked');
        }, 1000)
      );
    }
  });
  </script>
  
  <style lang="scss" scoped>
  </style>
  

效果

节流

throttle.ts

export function throttle(func: (...args: any[]) => void, limit: number) {
    let inThrottle: boolean;
    return function (this: any, ...args: any[]) {
      if (!inThrottle) {
        func.apply(this, args);
        inThrottle = true;
        setTimeout(() => inThrottle = false, limit);
      }
    };
  }
  

使用

<template>
    <button ref="submitButton">GET</button>
  </template>
  
  <script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { throttle } from '../utils/throttle';  // 导入节流函数
  
  // 使用 ref 访问 DOM 元素
  const submitButton = ref<HTMLElement | null>(null);
  
  onMounted(() => {
    if (submitButton.value) {
      submitButton.value.addEventListener(
        'click',
        throttle(() => {
          console.log('clicked');
        }, 1000)
      );
    }
  });
  </script>
  
  <style lang="scss" scoped>
  </style>
  

效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值