代码是基于 vue3.X
<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>