1. Concept
- Hook is the meaning of hook,
hooks
which is similar to js files that encapsulate public methods to realize the reuse of functions. hooks
Clear source of reuse function code, clear and easy to understand- 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
src
Create ahooks
folder in to store thehook
files in- According to the function/method needs, you can create a new file file name
hooks
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';