赞
踩
一、概念
hooks
类似于封装公共方法的 js文件,实现功能的重复利用。hooks
清楚复用功能代码的来源, 清晰易懂二、hooks的命名
函数名/文件名,以use开头,形如: useXX
三、hooks的使用
src
中创建一个hooks
文件夹,用来存放hook
文件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;
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
3. 在需要的地方先导入hook
文件,然后在
的使用
import useResize from '@/hooks/useResize';
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。