Ben Lin
2025-03-08 745815f637e5385b2cbc23a6ae02401bb8b6c675
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<template>
  <SvgIcon
    :size="size"
    :name="getSvgIcon"
    v-if="isSvgIcon"
    :class="[$attrs.class, 'anticon']"
    :spin="spin"
  />
  <span
    v-else
    ref="elRef"
    :class="[$attrs.class, 'app-iconify anticon', spin && 'app-iconify-spin']"
    :style="getWrapStyle"
  ></span>
</template>
<script lang="ts" setup>
  import type { PropType } from 'vue';
  import { ref, watch, onMounted, nextTick, unref, computed, CSSProperties } from 'vue';
  import SvgIcon from './src/SvgIcon.vue';
  import Iconify from '@purge-icons/generated';
  import { isString } from '@/utils/is';
  import { propTypes } from '@/utils/propTypes';
 
  const SVG_END_WITH_FLAG = '|svg';
 
  defineOptions({ name: 'Icon' });
 
  const props = defineProps({
    // icon name
    icon: propTypes.string,
    // icon color
    color: propTypes.string,
    // icon size
    size: {
      type: [String, Number] as PropType<string | number>,
      default: 16,
    },
    spin: propTypes.bool.def(false),
    prefix: propTypes.string.def(''),
  });
 
  const elRef = ref(null);
 
  const isSvgIcon = computed(() => props.icon?.endsWith(SVG_END_WITH_FLAG));
  const getSvgIcon = computed(() => props.icon.replace(SVG_END_WITH_FLAG, ''));
  const getIconRef = computed(() => `${props.prefix ? props.prefix + ':' : ''}${props.icon}`);
 
  const update = async () => {
    if (unref(isSvgIcon)) return;
 
    const el: any = unref(elRef);
    if (!el) return;
 
    await nextTick();
    const icon = unref(getIconRef);
    if (!icon) return;
 
    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);
    }
  };
 
  const getWrapStyle = computed((): CSSProperties => {
    const { size, color } = props;
    let fs = size;
    if (isString(size)) {
      fs = parseInt(size, 10);
    }
 
    return {
      fontSize: `${fs}px`,
      color: color,
      display: 'inline-flex',
    };
  });
 
  watch(() => props.icon, update, { flush: 'post' });
 
  onMounted(update);
</script>
<style lang="less">
  .app-iconify {
    display: inline-block;
    // vertical-align: middle;
 
    &-spin {
      svg {
        animation: loadingCircle 1s infinite linear;
      }
    }
  }
 
  span.iconify {
    display: block;
    min-width: 1em;
    min-height: 1em;
    border-radius: 100%;
    background-color: @iconify-bg-color;
  }
</style>