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