hooks in vue3

1. Concept

  1. Hook is the meaning of hook, hookswhich is similar to js files that encapsulate public methods to realize the reuse of functions.
  2. hooks Clear source of reuse function code, clear and easy to understand
  3. Hooks solve the problem of mixin :
  • The logic of mixins  is nested with each other, the source of data is unknown, and the state cannot be transferred to each other

Second, the naming of hooks

  Function name/file name, starting with use, like: useXX

3. The use of hooks

  1. srcCreate a hooksfolder in to store the hookfiles in
  2. According to the function/method needs, you can create a new file file namehooks in the folder.ts
import { useDebounceFn } from '@vueuse/core';

// type Ignore = {
//   collapse?: boolean; // 忽略菜单折叠
//   fullscreen?: boolean; // 忽略全屏
//   splitter?: boolean; // 忽略splitter size改变
// };
type Item = 'collapse' | 'fullscreen' | 'splitter';
type Ignores = [Item] | [Item, Item] | [Item, Item, Item];

const useResize = (callback: () => any, ignore?: Ignores, initialDelay: 'infinity' | number = 0) => {
  const store = useStore();

  const debounceFn = useDebounceFn(callback, 300);

  watch(
    () => store.isCollapse,
    () => {
      if (ignore?.includes('collapse')) return;
      debounceFn();
    }
  );

  watch(
    () => store.isFullscreen,
    () => {
      if (ignore?.includes('fullscreen')) return;
      debounceFn();
    }
  );

  watch(
    () => store.lastSplitterUpdateTime,
    () => {
      if (ignore?.includes('splitter')) return;
      debounceFn();
    }
  );

  onMounted(async () => {
    window.addEventListener('resize', debounceFn);

    if (initialDelay !== 'infinity') {
      await sleep(initialDelay);
      callback();
    }
  });

  onBeforeUnmount(() => {
    window.removeEventListener('resize', debounceFn);
  });
};

export default useResize;

3. The use of importing first where neededhook文件,然后在

import useResize from '@/hooks/useResize';

Guess you like

Origin blog.csdn.net/qq_39029949/article/details/130248477