vue封装全局的防抖节流函数

1.在入口文件main.js中:

//防抖函数
export let debounce = (() => {
  let instances = []
  return function (fun, delay = 300) {
    //项目中,多个地方用到防抖,进行判断,每次调用全局的防抖函数,是否是同一块代码
    const stackLines = new Error().stack.split('\n');
    let callerLine = stackLines[2];
    
    //判断数组中是否有了
    let index = instances.findIndex(item => {
      return item.callerLine == callerLine
    })
    if (index < 0) {
      //没有的话,直接新增一个
      instances.push({ callerLine, fun, delay, timer: null })
      index = instances.length - 1
    } else {
      //有了的话,直接将传递的逻辑函数赋值进去
      instances[index].fun = fun
    }

    //找到数据中对应的对象
    let instance = instances[index]
    let ctx = this
    let args = arguments
    //有时间间隔器,则清除
    if (instance.timer) {
      clearTimeout(instance.timer)
    }
    //进行其他逻辑
    instance.timer = setTimeout(() => {
      instance.timer = null
      instance.fun.apply(ctx, args)
    }, instance.delay)
  }
})()

//节流函数
export let throttle = (() => {
  let instances = []
  return function (fun, delay = 300) {
    const stackLines = new Error().stack.split('\n');
    let callerLine = stackLines[2];
    let index = instances.findIndex(item => {
      return item.callerLine == callerLine
    })
    if (index < 0) {
      instances.push({ callerLine, fun, delay, timeout: null })
      index = instances.length - 1
    } else {
      instances[index].fun = fun
    }
    let instance = instances[index]
    let args = arguments;//注意如果要传参的话 这句不能省略
    if (!instance.timeout) {
      instance.timeout = setTimeout(() => {
        instance.timeout = null;
        instance.fun.apply(this, args)
      }, instance.delay)
    }
  }
})()

Vue.prototype.$debounce = debounce;
Vue.prototype.$throttle = throttle;

2.页面中使用:

<div id="watch-example">
            <p>
                问一个是否的问题:
                <input v-model="question2">
            </p>
            <p>{{ answer2 }}</p>
        </div>
data() {
        return {
            question2: '',
            answer2: '请输入问题,否则我无法回答你!'
        };
    },

 

watch: {
        question2: function (newQuestion, oldQuestion) {
            this.answer2 = '请等待!';
            this.$debounce(this.getAnswer2, 1000);
        }
    },

 

getAnswer2: function() {
            if (this.question.indexOf('?') === -1) {
                this.answer2 = '请输入疑问句!';
                return;
            }else{
                this.answer2 = '请稍后...';
            setTimeout(() => {
                this.answer2 = '章总';
            }, 1000)
            }
            
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值