VUE里面用ES6 Proxy 封装防抖、节流函数

在VUE里面用ES6的Proxy封装防抖、节流函数,并在组件里面使用

在我的项目目录src/utils下面新建一个currencyFunction.js用来放一些通用的全局函数
在这里插入图片描述

在js文件抛出方法

/**
 * 通用防抖函数
 * fn:传入的方法
 * rate:延迟时间 毫秒 时间内再次触发刷新时间
 * immediate:true 立即执行      false 不立即执行
 * **/
export function debounce(fn, rate=300,immediate=true) {
    let timer;
    return new Proxy(fn, {
        apply(target, ctx, args) {
            if (timer) {
            	clearTimeout(timer);
            }
            if(immediate){
                let callNow = !timer;
                timer = setTimeout(() => {
                    timer = null;
                }, rate)
                if (callNow) {
                    return Reflect.apply(target, ctx, args);
                }
            }else{
                timer = setTimeout(() => {
                    return Reflect.apply(target, ctx, args);
                }, rate)
            }

        },
    })
}
/**
 * 通用节流函数
 * fn:传入的方法
 * rate:时间 毫秒  规定时间内触发第一次
 * **/
export function throttle (fn, rate=1000)  {
    let lastTime = 0;
    return new Proxy(fn, {
        apply(target, ctx, args) {
            const now = Date.now();
            if (now - lastTime > rate) {
                lastTime = now;
                return Reflect.apply(target, ctx, args);
            }
        },
    });
};

在组件里面使用

<script>
import {debounce, throttle} from '@/utils/currencyFunction'
export default {
    data() {
        return {
            
        };
    },
    methods: {
        changeSelect:throttle((value)=>{
            console.log('调用测试方法',value)
        },5000),
    }
};
</script>
<think>好的,我现在需要帮助用户解决在Vue3中全局封装防抖节流函数的问题。首先,我得回忆一下防抖节流的基本概念以及它们在Vue中的应用场景。防抖(debounce)是指在一定时间内只执行最后一次操作,常用于输入框搜索建议;而节流(throttle)则是每隔一定时间执行一次,适用于滚动事件或窗口调整等高频触发的情况。 用户的需求是全局封装,这意味着他们希望在整个Vue应用中方便地使用这些函数,而不必在每个组件中单独引入或定义。根据之前的引用内容,用户可能已经看过一些Vue2和Vue3的示例,但需要更具体的Vue3全局方法。 接下来,我需要考虑Vue3的全局特性,比如使用app.config.globalProperties来添加全局属性或方法。同时,Vue3的组合式API可能会影响封装的方式,但用户可能更倾向于传统的方法封装,以便在模板中直接使用。 然后,参考用户提供的引用,特别是引用[2]、[4]和[5],其中提到了使用闭包和setTimeout实现防抖节流。需要将这些方法适配到Vue3的全局上下文中。例如,在Vue3中,可以通过插件的形式封装,然后在main.js中安装,这样所有组件都可以访问。 另外,用户提供的示例代码中有一些实现细节需要注意,比如防抖函数中的立即执行选项,以及节流函数中定时器的管理。确保封装后的函数能够正确处理this上下文,这在Vue3中可能有所不同,因为组合式API更推荐使用setup函数,但全局方法可能仍然需要绑定到实例上。 然后,我需要考虑如何编写示例代码,展示如何在组件中使用这些全局方法。比如,在模板中使用@click="throttle(handleClick, 1000)",或者在方法中调用this.debounce(...)。同时,需要确保TS类型声明(如果用户使用TypeScript)或者至少提供基本的类型提示。 可能还需要处理一些边缘情况,比如函数参数的传递、取消未执行的防抖节流函数等。不过,根据用户的需求,可能只需要基础实现即可,高级功能可以后续扩展。 最后,要生成相关问题,帮助用户进一步学习,比如性能优化、应用场景、与第三方库的比较等。这些问题应该与封装全局函数相关,并且基于用户之前的问题,引导他们深入理解。 总结步骤: 1. 定义防抖节流函数,使用闭包和定时器。 2.Vue3中通过app.config.globalProperties注册为全局方法。 3. 创建Vue插件以便于安装。 4. 在main.js中安装插件。 5. 提供组件中的使用示例,包括事件处理和方法调用。 6. 添加TypeScript类型声明(可选但推荐)。 7. 生成相关问题,促进深入学习。</think>### Vue3 全局防抖/节流函数封装指南 在Vue3中全局封装防抖(debounce)和节流(throttle)函数,可以通过以下步骤实现: #### 一、核心实现原理 1. **防抖函数**:延迟执行直到停止触发后的指定时间$t$,若重复触发则重新计时[^2] $$f_{debounce}(f,t) = \lim_{n→∞} \underbrace{\text{setTimeout}(f,t)}_{\text{每次触发重置计时器}}$$ 2. **节流函数**:固定时间间隔$t$内只执行一次,稀释触发频率[^4] $$f_{throttle}(f,t) = \begin{cases} \text{立即执行} & \text{首次触发} \\ \text{锁定执行} & \text{间隔期内} \end{cases}$$ #### 二、全局封装实现 ```typescript // utils/throttleDebounce.ts type Func = (...args: any[]) => void; export const debounce = (fn: Func, delay = 300) => { let timer: ReturnType<typeof setTimeout>; return (...args: any[]) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; }; export const throttle = (fn: Func, limit = 300) => { let throttling = false; return (...args: any[]) => { if (!throttling) { fn(...args); throttling = true; setTimeout(() => throttling = false, limit); } }; }; ``` #### 三、注册全局属性 ```typescript // plugins/throttleDebounce.ts import { App } from 'vue'; import { debounce, throttle } from '@/utils/throttleDebounce'; export default { install(app: App) { app.config.globalProperties.$debounce = debounce; app.config.globalProperties.$throttle = throttle; } }; ``` #### 四、在main.ts中安装 ```typescript import { createApp } from 'vue' import throttleDebounce from './plugins/throttleDebounce' const app = createApp(App) app.use(throttleDebounce) ``` #### 五、组件中使用示例 ```vue <template> <!-- 按钮防抖点击 --> <button @click="$debounce(submitForm, 500)">提交</button> <!-- 滚动节流 --> <div @scroll="$throttle(handleScroll, 1000)"></div> </template> <script setup> // 方法级使用 const searchInput = (text) => { console.log('Search:', text); } const debouncedSearch = debounce(searchInput, 500); </script> ``` #### 六、TS类型增强(可选) ```typescript // global.d.ts declare module '@vue/runtime-core' { interface ComponentCustomProperties { $debounce: (fn: (...args: any[]) => void, delay?: number) => void; $throttle: (fn: (...args: any[]) => void, limit?: number) => void; } } ``` #### 最佳实践建议: 1. **参数传递**:使用箭头函数保持上下文 ```vue <button @click="$debounce(() => saveData(id), 500)"></button> ``` 2. **事件对象处理**:需要显式传递event对象 ```vue <input @input="$debounce((e) => search(e.target.value), 300)" /> ``` 3. **内存管理**:在组件卸载时清除定时器 ```typescript onUnmounted(() => { clearTimeout(timer); throttling = false; }); ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值