踩坑记录:vue使用debounce函数

正确写法:

<template>
  <h-page-container>
    <el-button @click="handleClick()">点我</el-button>
  </h-page-container>
</template>
<script>
import { debounce } from './common.js'
export default {
  name: 'Hello',
  data () {
    return {
    }
  },
  methods: {
    handleClick: debounce(function () { // 问题一:handleClick: debounce的写法有什么用?
      this.clg()
    }, 200),
    clg () {
      console.log('111111')
    }
  }
}
</script>

debounce是已经准备好的:

/**
 * 函数防抖
 */
export function debounce (fn, delay) {
  // 记录上一次的延时器
  let timer = null
  var delay = delay || 200
  return function () {
    const args = arguments
    const that = this
    // 清除上一次延时器
    clearTimeout(timer)
    timer = setTimeout(function () {
      fn.apply(that, args)
    }, delay)
  }
}

问题一:handleClick: debounce的写法有什么用?

handleClick: debounce相当于:

<template>
  <h-page-container>
    <el-button @click="handleClick()">点我</el-button>
  </h-page-container>
</template>
<script>
import { debounce } from './common.js'
export default {
  name: 'Hello',
  data () {
    return {
      test: debounce(function () {
        this.clg()
      }, 200)
    }
  },
  methods: {
    handleClick () {
      this.test()
    },
    clg () {
      console.log('111111')
    }
  }
}
</script>

但是当我改写成下面这种写法时,clg在被我点击时就直接触发了(点击了多少次就会延迟200ms后再执行多少次clg),并没有实现节流的效果,我猜想是加了一个()导致他的返回值立刻执行了。但是为什么写成this.test()就不会被立刻执行呢?

handleClick () {
      const that = this
      debounce(function () {
        that.clg()
      }, 200)()
    },

是因为上面两种写法debounce其实只在页面渲染的时候执行了一次。但是最后一种写法他每次点击都会被执行,加入事件队列,然后再delay之后依次执行。

最最最简单就是自个在页面里写防抖,看半天他那封装原理没卵用,不如去花时间看看别的。

<template>
  <h-page-container>
    <el-button @click="handleClick()">点我</el-button>
  </h-page-container>
</template>
<script>
export default {
  name: 'Hello',
  data () {
    return {
      timer: null
    }
  },
  methods: {
    handleClick () {
      clearTimeout(this.timer)
      this.timer = setTimeout(function () {
        console.log('111111')
      }, 200)
    }
  }
}
</script>

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值