vue3의 후크

1. 개념

  1. 후크 는 후크의 의미로, hooks함수의 재사용을 실현하기 위해 공용 메소드를 캡슐화하는 js 파일과 유사합니다.
  2. hooks 명확한 재사용 기능 코드 소스, 명확하고 이해하기 쉬운
  3. 후크는 mixin 문제를 해결합니다 .
  • 믹스인  의 로직 은 서로 중첩되어 있고 데이터 소스를 알 수 없으며 상태를 서로 전송할 수 없습니다.

둘째, 후크의 이름 지정

  다음과 같이 use로 시작하는 함수 이름/파일 이름: useXX

3. 후크 사용

  1. 파일 저장할 폴더를 src만듭니다.hookshook
  2. 기능/방법 필요에 따라 hooks폴더에 새 파일 파일 이름을 만들 수 있습니다..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. 필요한 경우 먼저 가져오기 사용hook文件,然后在

import useResize from '@/hooks/useResize';

Supongo que te gusta

Origin blog.csdn.net/qq_39029949/article/details/130248477
Recomendado
Clasificación