vue的节流与防抖的封装使用

建一个js文件

// 节流

export function throttle(fn, delay = 500) {

  let valid = true

  return function() {

    if (!valid) {

      return false

    }

    valid = false

    setTimeout(() => {

      fn()

      valid = true

    }, delay)

  }

}

// 防抖

export function debounce(fn, delay = 500) {

  let timer = null

  return function() {

    if (timer) clearTimeout(timer)

    timer = setTimeout(() => {

      fn.apply(this, arguments)

      timer = null

    }, delay)

  }

}

以上是封装

this.getData() 比如是搜索按钮

引用 

import { debounce } from '@/utils' // 防抖  文件所在的位置

getData:debounce( function() {

请求内容

},可写可不写(不写默认500) )

### Vue3 中实现防抖节流函数的封装Vue3 应用程序中,可以利用 `lodash` 或者更轻量级的 `throttle-debounce` 库来实现防抖 (debounce) 和节流 (throttle) 功能。为了更好地集成这些功能到组件逻辑内,推荐创建自定义组合式 API 函数。 #### 使用 throttle-debounce 实现 Debounce 和 Throttle 封装 ```javascript // useDebouncedRef.js import { ref, watch } from 'vue'; import { debounce as db, throttle as th } from 'throttle-debounce'; export function useDebouncedRef(initialValue, delay) { const value = ref(initialValue); const debouncedValue = ref(initialValue); const updateHandler = () => { debouncedValue.value = value.value; }; // 创建一个取消函数以便清理副作用 let cancel; if (!cancel) { cancel = db(delay, updateHandler); } watch(value, () => { cancel(); }); return { value, debouncedValue, }; } export function useThrottledRef(initialValue, limit) { const value = ref(initialValue); const throttledValue = ref(initialValue); const updateHandler = () => { throttledValue.value = value.value; }; // 创建一个取消函数以便清理副作用 let cancel; if (!cancel) { cancel = th(limit, updateHandler); } watch(value, () => { cancel(); }); return { value, throttledValue, }; } ``` 通过上述代码片段,在任何 Vue 组件都可以轻松引入并应用这两个钩子函数[^1]: ```html <template> <div> <!-- 输入框 --> <input v-model="searchQuery.value" placeholder="Search..." /> <!-- 显示未处理过的输入值 --> <p>Raw Input Value: {{ searchQuery.value }}</p> <!-- 显示经过防抖后的最终结果 --> <p>Debounced Result After Delay: {{ debouncedResult.debouncedValue }}</p> <!-- 显示经过节流后的最新一次更新的结果 --> <p>Throttled Last Updated Value Within Interval: {{ throttledResult.throttledValue }}</p> </div> </template> <script setup> import { onMounted, reactive } from 'vue'; import { useDebouncedRef, useThrottledRef } from './useDebouncedRef'; const searchQuery = reactive({ value: '' }); const debouncedResult = useDebouncedRef('', 500); // 设置延迟时间为500毫秒 const throttledResult = useThrottledRef('', 1000); // 设置时间间隔为1秒钟 onMounted(() => { // 当页面加载完成时初始化监听器 }); </script> ``` 此示例展示了如何将防抖节流应用于用户输入场景下,从而减少不必要的计算开销以及提高用户体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值