首页 > 其他 > 详细

Vue中使用防抖或节流

时间:2020-01-16 17:29:45      阅读:1178      评论:0      收藏:0      [点我收藏+]

首先,需要先写好一个防抖函数或节流函数

// 防抖函数
export function debounce(fn, delay){
  let timeout = null
  return function(){
    let args = arguments
    if(timeout) window.clearTimeout(timeout)
    timeout = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}
// 节流函数
export function throttle(fn, wait){
  let timeout = null
  return function(){
    let args = arguments
    if(!timeout){
      timeout = setTimeout(() => {
        timeout = null
        fn.apply(this, args)
      }, delay)
    }
  }
}

 

然后,在vue文件中引用,并调用:

methods: {
  handleClick(){
    this.debounce(this)
  },
  debounce: debounce((vm) => {
    // do something,这里this不指向Vue实例,用vm传入
  }, 1000),
}

 

节流同理。

Vue中使用防抖或节流

原文:https://www.cnblogs.com/syll/p/12202347.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!