useComponentScale.ts
1.44 KB
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
import { CSSProperties, computed, unref, watch } from 'vue';
import { ComponentPropsConfigType } from '../index.type';
import { componentOptionsInitConfig } from '../publicConfig';
export const useComponentScale = (props: { config: ComponentPropsConfigType }, onScale?: Fn) => {
  const getRatio = computed(() => {
    try {
      const { option, attr } = props.config;
      const { w, h } = attr;
      const { widthPx, heightPx, itemWidthRatio, itemHeightRatio } = option;
      const currentW = (widthPx * itemWidthRatio) / 100;
      const currentH = (heightPx * itemHeightRatio) / 100;
      const widthScaleRatio = currentW / w;
      const heightScaleRatio = currentH / h;
      return Math.min(widthScaleRatio, heightScaleRatio);
    } catch (error) {
      return 1;
    }
  });
  const getScaleRadio = computed(() => {
    try {
      const { persetOption = {} } = props.config;
      const {
        maxScale = componentOptionsInitConfig.maxScale,
        minScale = componentOptionsInitConfig.minScale,
      } = persetOption;
      let ratio = unref(getRatio);
      ratio = ratio > maxScale! ? maxScale! : ratio < minScale! ? minScale! : ratio;
      return ratio;
    } catch (error) {
      return 1;
    }
  });
  const getScale = computed<CSSProperties>(() => {
    return { transform: `scale(${unref(getScaleRadio)})` };
  });
  onScale &&
    watch(getRatio, () => {
      onScale?.();
    });
  return { getScale, getScaleRadio, getRatio };
};