• 前端搜索框防抖函数应用


    防抖函数基本原理:setTimeout和clearTimeout的运用

    关键代码:

    let timer:any=null;

    if(timer) {
         clearTimeout(timer)
    }

     timer = setTimeout(() => {
          // ...略
     }, delay);

    防抖函数钩子文件:

    1. import { ref, watch, type Ref, type UnwrapRef, onUnmounted } from "vue";
    2. // 优化抖动问题
    3. interface IDebounceFn<T> {
    4. (...args : T[]) : void | Promise<void>
    5. }
    6. // 普通防抖函数(利用setTimeout, clearTimeout, 闭包)
    7. export const debounceFn = <T>(fn: IDebounceFn<T>, delay: number) => {
    8. let timer:any = null;
    9. function f(this:void, ...args:T[]) {
    10. if(timer) {
    11. clearTimeout(timer)
    12. }
    13. timer = setTimeout(() => {
    14. fn.call(this, ...args);
    15. }, delay);
    16. }
    17. return f;
    18. }
    19. // 钩子函数可以使用很多vue自带的比如watch, computed, ref, 生命周期钩子等(如果要用于react, 就使用react相关的钩子, 生命周期等, 基本逻辑差不多)
    20. const useDebounce=<T>(value:Ref<T>, delay:number)=> {
    21. const debounceValue = ref(value.value)
    22. let timer:any=null;
    23. const unwatch = watch(
    24. value,
    25. (nv) => {
    26. if(timer) {
    27. clearTimeout(timer)
    28. }
    29. timer = setTimeout(() => {
    30. debounceValue.value = nv as UnwrapRef<T>
    31. }, delay);
    32. }
    33. )
    34. onUnmounted(() => {
    35. // 避免一直watch
    36. unwatch()
    37. })
    38. return debounceValue;
    39. }
    40. export default useDebounce;

    使用普通防抖函数debounceFn的时候:

    1. const searchValue = ref(''); // 存储输入框的值
    2. const bounceWatch = (nv:string)=> {
    3. if(!nv) {
    4. // 搜索结果清空, 代码略
    5. }
    6. // 触发搜索函数, 代码略
    7. }
    8. watch(searchValue, debounceFn(bounceWatch, 1000)); // 监听输入框的值,防止调用太多查询接口,输入完成后才调用接口查询

    使用useDebounce钩子函数时:
     

    1. const searchValue = ref(''); // 存储输入框的值
    2. const bounceWatch = (nv:string)=> {
    3. if(!nv) {
    4. // 搜索结果清空, 代码略
    5. }
    6. // 触发搜索函数, 代码略
    7. }
    8. // 利用防抖函数获取搜索框的值,再监听该值,输入完成后再调用查询接口
    9. const debounceValue = useDebounce(searchValue, 1000)
    10. watch(debounceValue, bounceWatch)

  • 相关阅读:
    JAVA计算机毕业设计电影网站系统设计Mybatis+系统+数据库+调试部署
    Debug和Release的区别
    算法训练day37|贪心算法 part06(LeetCode738.单调递增的数字)
    ETLCloud助力富勒TMS实现物流数仓同步
    Java计算机毕业设计德云社票务系统源码+系统+数据库+lw文档
    MySQL SQL性能优化方案(SQL优化 二)
    Python+selenium自动化生成测试报告
    C++学习笔记(17)
    Qt的复杂代理使用总结
    java实现http/https请求
  • 原文地址:https://blog.csdn.net/qq_42750608/article/details/133151391