废话少说,直接看代码:
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后台管理系统