useAdaptiveWidth.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /**
  2. * 自适应宽度构造器
  3. *
  4. * @time 2022-4-8
  5. * @author sunjianlei
  6. */
  7. import { ref } from 'vue';
  8. import { useDebounceFn, tryOnUnmounted } from '@vueuse/core';
  9. import { useEventListener } from '/@/hooks/event/useEventListener';
  10. // key = js运算符+数字
  11. const defWidthConfig: configType = {
  12. '<=565': '100%',
  13. '<=1366': '800px',
  14. '<=1600': '600px',
  15. '<=1920': '600px',
  16. '>1920': '500px',
  17. };
  18. type configType = Record<string, string | number>;
  19. /**
  20. * 自适应宽度
  21. *
  22. * @param widthConfig 宽度配置,可参考 defWidthConfig 配置
  23. * @param assign 是否合并默认配置
  24. * @param debounce 去抖毫秒数
  25. */
  26. export function useAdaptiveWidth(widthConfig = defWidthConfig, assign = true, debounce = 50) {
  27. const widthConfigAssign = assign ? Object.assign({}, defWidthConfig, widthConfig) : widthConfig;
  28. const configKeys = Object.keys(widthConfigAssign);
  29. const adaptiveWidth = ref<string | number>();
  30. /**
  31. * 进行计算宽度
  32. * @param innerWidth
  33. */
  34. function calcWidth(innerWidth) {
  35. let width;
  36. for (const key of configKeys) {
  37. try {
  38. // 通过js运算
  39. let flag = new Function(`return ${innerWidth} ${key}`)();
  40. if (flag) {
  41. width = widthConfigAssign[key];
  42. break;
  43. }
  44. } catch (e) {
  45. console.error(e);
  46. }
  47. }
  48. if (width) {
  49. adaptiveWidth.value = width;
  50. } else {
  51. console.warn('没有找到匹配的自适应宽度');
  52. }
  53. }
  54. // 初始计算
  55. calcWidth(window.innerWidth);
  56. // 监听 resize 事件
  57. const { removeEvent } = useEventListener({
  58. el: window,
  59. name: 'resize',
  60. listener: useDebounceFn(() => calcWidth(window.innerWidth), debounce),
  61. });
  62. // 卸载组件时取消监听事件
  63. tryOnUnmounted(() => removeEvent());
  64. return { adaptiveWidth };
  65. }
  66. /**
  67. * 抽屉自适应宽度
  68. */
  69. export function useDrawerAdaptiveWidth() {
  70. return useAdaptiveWidth(
  71. {
  72. '<=620': '100%',
  73. '<=1600': 600,
  74. '<=1920': 650,
  75. '>1920': 700,
  76. },
  77. false
  78. );
  79. }