使用vue3的一些坑

js

防抖问题,防抖不生效

问题:1. 调用防抖方法,但是延时函数不执行
2.点击几次调用几次(没起到作用)

	// 修改前
    function debounce (fn, delay) {
      let timer
      return function () {
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(() => {
          fn()
        }, delay)
      }
    }

    // 修改后
   let timer = ref(null)
   function debounce (fn, delay) {
    // 这里返回的函数是每次用户实际调用的防抖函数
    // 如果已经设定过定时器了就清空上一次的定时器
    // 开始一个新的定时器,延迟执行用户传入的方法
     return function () {
       console.log('timer', timer);
       if (timer) {
         clearTimeout(timer)
       }
       timer = setTimeout(() => {
         fn()
       }, delay)
     }
   }
   
   // 调用失败  
    debounce(() => {
     console.log('点击')
    }, 1000)
    
    // 调用成功 解决
    debounce(function(){
      console.log("点击")
    },1000)()//加括号表示调用其返回的那个函数
     

参考链接https://blog.csdn.net/qinwei_123/article/details/96486483?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-4.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-4.control

参考链接https://blog.csdn.net/qq_41885295/article/details/110440371


版权声明:本文为weixin_44622464原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。