vue项目封装防抖节流函数、全局挂载

优点:

1、可以在methods方法中直接调用,无需重新定义方法承载,业务逻辑无需拆分;(调用方式在本文末尾)

2、可全局引入直接调用,无需其他操作;

/*
 * fun [function] 需要防抖的函数
 * delay [number] 毫秒,防抖期限值
 */
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
    }, instance.delay)
  }
})()
/*
 * fun [function] 需要节流的函数
 * delay [number] 毫秒,节流期限值
 */
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)
    }
  }
})()

两个自执行函数放在了utils文件夹下index.js文件中,通过

import * as Util from '@/utils'
Vue.prototype.$util = Util

进行了全局挂载,可根据实际情况需要进行引入或者全局挂载

调用方式

input、button中绑定方式

 <el-button size="mini" @click="$util.debounce(infraSetFocus, 300)">测试</el-button>

 methods方法中调用方式

  methods: { 
//....
        test() {//频繁调用函数
            // 一些其他逻辑......
            this.$util.debounce(() => {
                //    防抖逻辑
            }, 2000)
        },
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值