防抖封装函数及引用讲解

文章介绍了如何在Vue2项目中使用防抖函数(debounce)来优化事件处理,特别是在频繁触发的场景下,如按钮点击。通过创建一个debounce函数,接收that、执行函数fun和等待时间wait作为参数,确保函数在设定的时间间隔内只执行一次。在Test.vue组件中,将debounce应用到textFunDebounce方法,以此来调用需要防抖的textFun方法,避免在短时间内多次执行。
摘要由CSDN通过智能技术生成
// 节流
export const debounce = (that, fun, wait) => {
  if (that.timer) { 
    clearTimeout(that.timer); 
  }
  that.timer = setTimeout(() => {
    fun();
  }, wait);
}

具体使用 -- VUE2环境下

<script>
    //注意,这里模拟的是VUE文件的环境状态下,按步骤直接套用即可
    //外部JS文件 public.js
    // export const debounce = (that, fun, wait) => {
    // if (that.timer) { clearTimeout(that.timer); }
    // that.timer = setTimeout(() => {
    // fun();
    // }, wait);
    // }
    //由于此处用的是箭头函数,所以内部不能用this,通过外部传入解决,参数为that
    //fun,为传入函数
    //wait,为时间
    </script>

<!-- Test.vue -->
    <template>
    <!-- 此处模拟vue的渲染区,@click调用防抖后函数 -->
    <div class="operate">
        <el-button type="success" @click="textFunDebounce">Enter  确定</el-button>
</div>
</template>
<script>
            import { debounce } from "@/src/util/public";
export default {
    methods: {
        //调用防抖
        textFunDebounce() {
            //第一个this,为参数that的实际传参,解决指向问题
            //this.textFun为传入函数,由于此函数需要传参,所以后面使用 .bind(this,参数) 进行 —— 此项请各自查资料
            //300,为防抖时间
            debounce(this,this.textFun.bind(this,"我是传参page"),300)
        },
        //需要防抖的函数
        textFun(page) {
            console.log("延迟成功", page);
        }
    }
}
</script>

TypeScript(简称TS)是一种由微软开发的开源编程语言,它是JavaScript的一个超集,可以编译成纯JavaScript代码。在TS中,我们可以使用装饰器和泛型等特性来封装防抖节流函数防抖函数和节流函数都是用于控制函数执行频率的方法,常用于优化性能和避免重复触发事件。 防抖函数的作用是在一定时间内,如果事件持续触发,则重新计时,直到事件停止触发后才执行函数。常见的应用场景是输入框搜索联想功能。 节流函数的作用是在一定时间内,无论事件触发多少次,只执行一次函数。常见的应用场景是滚动加载数据。 下面是一个使用TS封装防抖节流函数的示例: ```typescript // 防抖函数 function debounce(func: Function, delay: number): Function { let timer: number | null = null; return function (...args: any[]) { if (timer) { clearTimeout(timer); } timer = setTimeout(() => { func.apply(this, args); }, delay); }; } // 节流函数 function throttle(func: Function, delay: number): Function { let timer: number | null = null; return function (...args: any[]) { if (!timer) { timer = setTimeout(() => { func.apply(this, args); timer = null; }, delay); } }; } ``` 使用示例: ```typescript function search(keyword: string) { // 模拟搜索功能 console.log(`Searching for ${keyword}`); } const debouncedSearch = debounce(search, 300); const throttledSearch = throttle(search, 300); debouncedSearch('apple'); debouncedSearch('banana'); debouncedSearch('cherry'); throttledSearch('apple'); throttledSearch('banana'); throttledSearch('cherry'); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值