debounce.vue 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <script setup lang="ts">
  2. import { ElMessage } from "element-plus";
  3. import { debounce } from "/@/utils/debounce";
  4. import { useDebounceFn, useThrottleFn } from "@vueuse/core";
  5. const handle = () => {
  6. ElMessage({
  7. message: "恭喜你,这是一条成功消息",
  8. type: "success"
  9. });
  10. };
  11. const immediateDebounce = debounce(handle, 1000, true);
  12. const debounceClick = useDebounceFn(handle, 1000);
  13. const throttleClick = useThrottleFn(handle, 1000, false);
  14. </script>
  15. <template>
  16. <div>
  17. <el-card class="mb-5">
  18. <template #header>
  19. <div>防抖:debounce</div>
  20. </template>
  21. <div class="mb-5">
  22. 所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n
  23. 秒内又触发了事件,则会重新计算函数执行时间。
  24. </div>
  25. <el-button @click="immediateDebounce">
  26. 连续点击我,只会执行最后一次点击事件,立即执行
  27. </el-button>
  28. <el-button @click="debounceClick">
  29. 连续点击我,只会执行最后一次点击事件,延后执行
  30. </el-button>
  31. </el-card>
  32. <el-card>
  33. <template #header>
  34. <div>节流:throttle</div>
  35. </template>
  36. <div class="mb-5">
  37. 所谓节流,就是指连续触发事件但是在 n
  38. 秒中只执行一次函数。节流会稀释函数的执行频率。
  39. </div>
  40. <el-button @click="throttleClick">
  41. 连续点击我,每一秒只会执行一次点击事件
  42. </el-button>
  43. </el-card>
  44. </div>
  45. </template>
  46. <style scoped></style>