当前位置:   article > 正文

vue3中的hooks_vue3的hooks

vue3的hooks

一、概念

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

二、hooks的命名

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

三、hooks的使用

  1. src中创建一个hooks文件夹,用来存放hook文件
  2. 根据功能/方法需要,可以在hooks文件夹中新建一个文件 文件名.ts
  1. import { useDebounceFn } from '@vueuse/core';
  2. // type Ignore = {
  3. // collapse?: boolean; // 忽略菜单折叠
  4. // fullscreen?: boolean; // 忽略全屏
  5. // splitter?: boolean; // 忽略splitter size改变
  6. // };
  7. type Item = 'collapse' | 'fullscreen' | 'splitter';
  8. type Ignores = [Item] | [Item, Item] | [Item, Item, Item];
  9. const useResize = (callback: () => any, ignore?: Ignores, initialDelay: 'infinity' | number = 0) => {
  10. const store = useStore();
  11. const debounceFn = useDebounceFn(callback, 300);
  12. watch(
  13. () => store.isCollapse,
  14. () => {
  15. if (ignore?.includes('collapse')) return;
  16. debounceFn();
  17. }
  18. );
  19. watch(
  20. () => store.isFullscreen,
  21. () => {
  22. if (ignore?.includes('fullscreen')) return;
  23. debounceFn();
  24. }
  25. );
  26. watch(
  27. () => store.lastSplitterUpdateTime,
  28. () => {
  29. if (ignore?.includes('splitter')) return;
  30. debounceFn();
  31. }
  32. );
  33. onMounted(async () => {
  34. window.addEventListener('resize', debounceFn);
  35. if (initialDelay !== 'infinity') {
  36. await sleep(initialDelay);
  37. callback();
  38. }
  39. });
  40. onBeforeUnmount(() => {
  41. window.removeEventListener('resize', debounceFn);
  42. });
  43. };
  44. export default useResize;

3. 在需要的地方先导入hook文件,然后在的使用

import useResize from '@/hooks/useResize';

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/257342
推荐阅读
相关标签
  

闽ICP备14008679号