UNPKG

vue-hooks-plus

Version:
47 lines (46 loc) 1.34 kB
import debounce from "lodash-es/debounce"; import { ref, watch, onUnmounted } from "vue"; function useDebounceFn(fn, options) { const optionsRef = ref(options || { wait: 1e3 }); const debouncedRef = ref(); const createDebounced = () => { const { wait = 1e3, ...rest } = optionsRef.value; return debounce(fn, wait, rest); }; debouncedRef.value = createDebounced(); watch( () => ({ ...optionsRef.value }), (newVal, oldVal) => { var _a; if (newVal.wait !== (oldVal == null ? void 0 : oldVal.wait) || newVal.maxWait !== (oldVal == null ? void 0 : oldVal.maxWait)) { (_a = debouncedRef.value) == null ? void 0 : _a.cancel(); debouncedRef.value = createDebounced(); } }, { deep: true } ); onUnmounted(() => { var _a; (_a = debouncedRef.value) == null ? void 0 : _a.cancel(); }); return { run: (...args) => { var _a; return (_a = debouncedRef.value) == null ? void 0 : _a.call(debouncedRef, ...args); }, cancel: () => { var _a; (_a = debouncedRef.value) == null ? void 0 : _a.cancel(); }, flush: () => { var _a; (_a = debouncedRef.value) == null ? void 0 : _a.flush(); }, updateOptions: (newOptions) => { optionsRef.value = newOptions; } }; } export { useDebounceFn as default };