Blame view

src/components/Icon/index.tsx 1.84 KB
vben authored
1
2
import './index.less';
陈文彬 authored
3
import type { PropType } from 'vue';
vben authored
4
5
6
7
8
9
10
11
12
13
import {
  defineComponent,
  ref,
  watch,
  onMounted,
  nextTick,
  unref,
  computed,
  CSSProperties,
} from 'vue';
陈文彬 authored
14
15
import Iconify from '@purge-icons/generated';
import { isString } from '/@/utils/is';
vben authored
16
import { propTypes } from '/@/utils/propTypes';
陈文彬 authored
17
18
19
20
export default defineComponent({
  name: 'GIcon',
  props: {
    // icon name
vben authored
21
    icon: propTypes.string,
陈文彬 authored
22
    // icon color
vben authored
23
    color: propTypes.string,
陈文彬 authored
24
25
26
    // icon size
    size: {
      type: [String, Number] as PropType<string | number>,
27
      default: 16,
陈文彬 authored
28
    },
vben authored
29
    prefix: propTypes.string.def(''),
陈文彬 authored
30
31
  },
  setup(props, { attrs }) {
vben authored
32
    const elRef = ref<ElRef>(null);
陈文彬 authored
33
34
35
36
37

    const getIconRef = computed(() => {
      const { icon, prefix } = props;
      return `${prefix ? prefix + ':' : ''}${icon}`;
    });
38
陈文彬 authored
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
    const update = async () => {
      const el = unref(elRef);
      if (el) {
        await nextTick();
        const icon = unref(getIconRef);

        const svg = Iconify.renderSVG(icon, {});

        if (svg) {
          el.textContent = '';
          el.appendChild(svg);
        } else {
          const span = document.createElement('span');
          span.className = 'iconify';
          span.dataset.icon = icon;
          el.textContent = '';
          el.appendChild(span);
        }
      }
    };
vben authored
60
61
62
63
64
65
66
67
68
69
70
71
    const wrapStyleRef = computed(
      (): CSSProperties => {
        const { size, color } = props;
        let fs = size;
        if (isString(size)) {
          fs = parseInt(size, 10);
        }
        return {
          fontSize: `${fs}px`,
          color,
          display: 'inline-flex',
        };
陈文彬 authored
72
      }
vben authored
73
    );
陈文彬 authored
74
vben authored
75
    watch(() => props.icon, update, { flush: 'post' });
76
陈文彬 authored
77
78
79
    onMounted(update);

    return () => (
80
      <div ref={elRef} class={[attrs.class, 'app-iconify anticon']} style={unref(wrapStyleRef)} />
陈文彬 authored
81
82
83
    );
  },
});