# 07. 图标选择器
URL: /%E6%96%87%E6%A1%A3/04.%E5%BC%80%E5%8F%91%E6%96%87%E6%A1%A3/01.%20%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91/01.%20%E5%9F%BA%E7%A1%80%E8%A7%84%E8%8C%83/07.%20%E5%9B%BE%E6%A0%87%E9%80%89%E6%8B%A9%E5%99%A8

项目中图标选择器、Iconify、Ant Design Vue 图标的使用说明


# 图标选择器与图标使用指南

> [!info] 项目当前使用 **@iconify/vue** 作为主要图标库，配合 UnoCSS 的 preset-icons 实现按需加载。

## 图标集预生成

在项目中，由于图标选择器的特殊性，需要预先指定并生成相应的文件以打包大量图标。以下是生成图标集的详细步骤：

## 图标集预生成

在项目中，由于图标选择器的特殊性，需要预先指定并生成相应的文件以打包大量图标。以下是生成图标集的详细步骤：

### 图标集生成步骤

1. **执行图标生成命令**：

   ```bash
   yarn gen:icon
   ```

2. **选择生成方式**：
   - 选择“local”表示本地生成，选择“online”表示在线生成。每种方式都有其优缺点，具体如下：
     - **本地生成**：将所有图标打包进 JavaScript 文件中，适用于无法访问外网的环境。
     - **在线生成**：在图标选择器使用图标时在线请求，并缓存到浏览器，减少代码打包体积。

![oqogf](https://storage.widiazine.top/obsidian/267a04c8b9b8f5205f22aa03bb2bfabe.webp)

1. **选择图标集**：
   - 根据提示选择要生成的图标集，并按回车确认。

![6gqt6](https://storage.widiazine.top/obsidian/2c1baecddd0b22938170617e8e9da5fc.webp)

1. **选择输出目录**：
   - 选择图标输出的目录，默认为 `src/components/Icon/data`，可以直接回车选择默认路径。

![w1ko7](https://storage.widiazine.top/obsidian/9d93147926a478fa94a826c1a2e08a6d.webp)

完成以上步骤后，图标集生成完成，图标选择器将包含所选图标集中的图标。注意，频繁更新图标集可能会导致图标丢失或显示不出来，特别是在本地生成的情况下。

### 生成方式的优缺点

- **在线图标（项目默认推荐）**：
  - 优点：有效减少代码打包体积，适用于可以访问外网的项目。
  - 缺点：在无法访问外网的环境中，图标可能无法显示。

- **本地图标**：
  - 优点：不依赖外网，适用于所有环境。
  - 缺点：打包体积较大，具体体积取决于所选图标集的图标数量。

## 组件库图标使用

### 使用 `ant-design-vue` 提供的图标

```vue
<template>
  <StarOutlined />
  <StarFilled />
  <StarTwoTone twoToneColor="#eb2f96" />
</template>

<script>
  import { defineComponent } from 'vue';
  import { StarOutlined, StarFilled, StarTwoTone } from '@ant-design/icons-vue';
  export default defineComponent({
    components: { StarOutlined, StarFilled, StarTwoTone },
  });
</script>
```

## Svg Sprite 图标

### 使用方法

1. **将 SVG 图标放置于 `src/assets/icons` 目录下**，例如：`test.svg`。

2. **使用 `SvgIcon` 组件展示图标**：

```vue
<template>
  <SvgIcon name="test" />
</template>

<script>
  import { defineComponent } from 'vue';
  import { SvgIcon } from '/@/components/Icon';
  export default defineComponent({
    components: { SvgIcon },
  });
</script>
```

3. **使用 `Icon` 组件展示图标**，以 `|svg` 结尾的图标名将自动使用 `SvgIcon` 组件：

```vue
<template>
  <Icon name="test|svg" />
</template>

<script>
  import { defineComponent } from 'vue';
  import { Icon } from '/@/components/Icon';
  export default defineComponent({
    components: { Icon },
  });
</script>
```

## Iconify 图标

项目中使用 [vite-plugin-purge-icons](https://github.com/antfu/purge-icons/blob/main/packages/vite-plugin-purge-icons/README.md) 插件实现 Iconify 图标。

1. **安装依赖**：

```bash
yarn add @iconify/iconify
yarn add @iconify/json @purge-icons/generated -D
```

2. **在 `vite.config.ts` 中引入插件**：

```typescript
import PurgeIcons from 'vite-plugin-purge-icons';

export default {
  plugins: [PurgeIcons()],
};
```

3. **编写 Icon 组件**，完整代码见 [src/components/Icon/src/Icon.vue](https://github.com/jeecgboot/jeecgboot-vue3/tree/master/src/components/Icon/src/Icon.vue)。

```vue
<template>
  <SvgIcon :size="size" :name="getSvgIcon" v-if="isSvgIcon" :class="[$attrs.class]" :spin="spin" />
  <span
    v-else
    ref="elRef"
    :class="[$attrs.class, 'app-iconify anticon', spin && 'app-iconify-spin']"
    :style="getWrapStyle"
  ></span>
</template>

<script lang="ts">
  import type { PropType } from 'vue';
  import {
    defineComponent,
    ref,
    watch,
    onMounted,
    nextTick,
    unref,
    computed,
    CSSProperties,
  } from 'vue';
  import SvgIcon from './SvgIcon.vue';
  import Iconify from '@purge-icons/generated';
  import { isString } from '/@/utils/is';
  import { propTypes } from '/@/utils/propTypes';

  const SVG_END_WITH_FLAG = '|svg';
  export default defineComponent({
    name: 'GIcon',
    components: { SvgIcon },
    props: {
      icon: propTypes.string,
      color: propTypes.string,
      size: {
        type: [String, Number] as PropType<string | number>,
        default: 16,
      },
      spin: propTypes.bool.def(false),
      prefix: propTypes.string.def(''),
    },
    setup(props) {
      const elRef = ref<ElRef>(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 = 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);

      return { elRef, getWrapStyle, isSvgIcon, getSvgIcon };
    },
  });
</script>

<style lang="less">
  .app-iconify {
    display: inline-block;
    &-spin {
      svg {
        animation: loadingCircle 1s infinite linear;
      }
    }
  }
  span.iconify {
    display: block;
    min-width: 1em;
    min-height: 1em;
    background-color: @iconify-bg-color;
    border-radius: 100%;
  }
</style>
```
