欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > vue3.0如何快速封装防抖和节流

vue3.0如何快速封装防抖和节流

2025/2/5 15:40:23 来源:https://blog.csdn.net/weixin_49573188/article/details/145175081  浏览:    关键词:vue3.0如何快速封装防抖和节流

废话少说,直接看代码:

import { ref, watch, onMounted, onUnmounted } from 'vue';// 防抖 hook
function useDebounce(value, delay) {const debouncedValue = ref(value);let handle;watch(value, (newValue) => {clearTimeout(handle);handle = setTimeout(() => {debouncedValue.value = newValue;}, delay);});onMounted(() => {debouncedValue.value = value;});onUnmounted(() => {clearTimeout(handle);});return debouncedValue;
}// 节流 hook
function useThrottle(value, limit) {const throttledValue = ref(value);let lastRun = 0;watch(value, (newValue) => {const now = Date.now();if (now - lastRun >= limit) {lastRun = now;throttledValue.value = newValue;}});onMounted(() => {throttledValue.value = value;});return throttledValue;
}export { useDebounce, useThrottle };

使用:

import { ref } from 'vue';
import { useDebounce } from './path-to-your-hooks'; // 替换为你的hooks文件路径export default {setup() {const inputVal = ref('');// 使用防抖 hookconst debouncedInputVal = useDebounce(inputVal, 500); // 500ms 的延迟return {inputVal,debouncedInputVal};}
};

最近发现一个比较好用的vue+node后台管理系统,vue2+vue3

如果你正在学习和了解node和vue结合,不妨看看它:点击直达vue+node后台管理系统

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com