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('');
// 使用防抖 hook
const debouncedInputVal = useDebounce(inputVal, 500); // 500ms 的延迟
return {
inputVal,
debouncedInputVal
};
}
};
最近发现一个比较好用的vue+node后台管理系统,vue2+vue3
如果你正在学习和了解node和vue结合,不妨看看它:点击直达vue+node后台管理系统
原文地址:https://blog.csdn.net/weixin_49573188/article/details/145175081
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!