vue 按钮的防抖和节流

1,695 阅读1分钟

( 代码是基于 vue3.X ) var timer = null, last = 0; 定义在函数外边才能达到效果,看网上的好多都定义在了函数的里面,那样在运行的时候不生效吧

<template>
  <div>
    <el-button  style="margin:20px 0;" type='primary' @click="fd">防抖事件</el-button>
    <div style="margin-bottom:40px">
      <span>防抖事件==>num:{{num}}</span>
    </div>
    <el-button type='primary' @click="jl">节流事件</el-button>
    <div style="margin:20px 0;">节流事件=> num1:{{num1}}</div>
  </div>
</template>

<script>
import { defineComponent, onMounted, toRefs, reactive, ref } from "vue";
var timer = null,
  last = 0;
export default defineComponent({
  setup() {
    var num = ref(0);
    var num1 = ref(0);
    function add() {
      num.value++;
    }
    var addjl = () => {
      num1.value++;
    };
    const methods = {
      fd() {
        methods.debounce(add, 3000);
      },
      jl() {
        methods.throttle(addjl, 3000);
      },
      // 节流
      throttle(fn, delay) {
        return (function (...args) {
          var nowTime = Date.now();
          if (nowTime - last > delay) {
            last = nowTime;
            fn.call(this, args);
          }
        })();
      },
      //  防抖
      debounce(fn, delay) {
        return (function (...args) {
          if (timer) {
            clearTimeout(timer);
          }
          timer = setTimeout(() => {
            fn.call(this, args);
          }, delay);
        })();
      },
    };
    return { ...methods, num, add, addjl, num1 };
  },
});
</script>

<style >
</style>