Pārlūkot izejas kodu

✨ 新增debounce/throttle hooks

晓晓晓晓丶vv 4 gadi atpakaļ
vecāks
revīzija
154ae0e4be

+ 16 - 0
src/hooks/useDebounce.ts

@@ -0,0 +1,16 @@
+import { Ref, ref, watch } from "vue";
+import useDebounceFn from "./useDebounceFn";
+
+const useDebounce = <T>(value: Ref<T>, ms = 200) => {
+  if (ms <= 0) return value;
+
+  const debounce = ref(value.value as T) as Ref<T>;
+
+  const updater = useDebounceFn(() => (debounce.value = value.value), ms);
+
+  watch(value, () => updater());
+
+  return debounce;
+};
+
+export default useDebounce;

+ 8 - 0
src/hooks/useDebounceFn.ts

@@ -0,0 +1,8 @@
+import { createFilterWrapper, debounceFilter } from "./utils";
+import { FunctionArgs } from "@/types/hooks";
+
+const useDebounceFn = <T extends FunctionArgs>(fn: T, ms = 200): T => {
+  return createFilterWrapper(debounceFilter(ms), fn);
+};
+
+export default useDebounceFn;

+ 18 - 0
src/hooks/useThrottle.ts

@@ -0,0 +1,18 @@
+import { Ref, ref, watch } from "vue";
+import useThrottleFn from "./useThrottleFn";
+
+const useThrottle = <T>(value: Ref<T>, delay = 200) => {
+  if (delay <= 0) return value;
+
+  const throttle: Ref<T> = ref(value.value as T) as Ref<T>;
+
+  const updater = useThrottleFn(() => {
+    throttle.value = value.value;
+  }, delay);
+
+  watch(value, () => updater());
+
+  return throttle;
+};
+
+export default useThrottle;

+ 12 - 0
src/hooks/useThrottleFn.ts

@@ -0,0 +1,12 @@
+import { FunctionArgs } from "@/types/hooks";
+import { createFilterWrapper, throttleFilter } from "./utils";
+
+const useThrottleFn = <T extends FunctionArgs>(
+  fn: T,
+  ms = 200,
+  trailing = true
+): T => {
+  return createFilterWrapper(throttleFilter(ms, trailing), fn);
+};
+
+export default useThrottleFn;

+ 19 - 0
src/types/hooks.d.ts

@@ -0,0 +1,19 @@
+export type Fn2 = () => void;
+
+export type FunctionArgs<Args extends any[] = any[], Return = void> = (
+  ...args: Args
+) => Return;
+
+export type EventFilter<Args extends any[] = any[], This = any> = (
+  invoke: Fn2,
+  options: FunctionWrapperOptions<Args, This>
+) => void;
+
+export interface FunctionWrapperOptions<
+  Args extends any[] = any[],
+  This = any
+> {
+  fn: FunctionArgs<Args, This>;
+  args: Args;
+  thisArgs: This;
+}