vue3中的hooks

一、概念

  1. hook是钩子的意思,hooks类似于封装公共方法的 js文件,实现功能的重复利用。
  2. hooks 清楚复用功能代码的来源, 清晰易懂
  3. hooks解决 mixin 的问题:
  • mixins 逻辑互相嵌套,数据来源不明,且不能互相传递状态

二、hooks的命名

  函数名/文件名,以use开头,形如: useXX

三、hooks的使用

  1. src中创建一个hooks文件夹,用来存放hook文件
  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';

猜你喜欢

转载自blog.csdn.net/qq_39029949/article/details/130248477