自留地第一锄,先把我每天
Cmd+C / Cmd+V
的图标方案刨出来,以后再也不用../assets/icon-xxx.svg
了。
1. 为什么选 Iconify
痛点 | 传统方案 | Iconify 方案 |
---|---|---|
图标源分散 | 阿里、Feather、Heroicons... 各装一个包 | 100+ 开源图标库 一个包全吃 |
编译体积 | 全量引入,打包 2 MB | 按需 CDN,只下当前图标 |
使用成本 | 先下载 → 再放 assets → 再 import | <iconify-icon icon="mdi:home" /> 一行搞定 |
可定制性 | 改颜色得开 Figma | 直接 class="text-red-500" Tailwind 即玩 |
2. 一分钟上车
① 安装
bash
# Vue3 官方组件
pnpm i @iconify/vue
# 如果还想离线,再装具体库(可选)
pnpm i @iconify-json/mdi
② 图标怎么找?
下面给出一份「从打开网页到把图标贴进代码」的完整动线,保证你 3 分钟就能搞定。
1️⃣ 打开官网
直达地址 → icon-sets.iconify.design/
2️⃣ 搜索图标
- 顶部搜索框输入关键词,例如
arrow
- 左侧可「按图标集过滤」:常用的是
mdi
、ep
、carbon
、ri
等 - 看到中意的图标后点进去,会打开「详情抽屉」
3️⃣ 复制「图标名」
在抽屉里找到 Icon name 这一行,形如
mdi:chevron-right
点击右侧复制按钮即可------这就是你在代码里唯一需要填的字符串。
ps:网站里面不好搜索的,不好找的图标 可以去:Yesicon - 精选全球高品质、开源、免费的矢量图标库 选中你想要的icon Vue 自动就会有 搭配 @iconify/vue 的哦,svg 、png 就更多啦~~
③ 最简裸用
xml
<template>
<Icon icon="mdi:home" class="text-2xl text-sky-600" />
</template>
<script setup>
import { Icon } from '@iconify/vue'
</script>
3. 自封装 <SvgIcon>
组件(双版本)
🔷 TS 版(已自用)
typescript
<script setup lang="ts">
import { computed, useAttrs } from 'vue'
import { Icon } from '@iconify/vue'
interface Props { icon?: string }
defineProps<Props>()
const attrs = useAttrs()
const bindAttrs = computed(() => ({
class: (attrs.class as string) || '',
style: (attrs.style as string) || '',
}))
</script>
<template>
<Icon :icon="icon" v-bind="bindAttrs" />
</template>
🔶 JS 版(无类型,直接抄)
xml
<script setup>
import { useAttrs, computed } from 'vue'
import { Icon } from '@iconify/vue'
defineProps({ icon: String })
const attrs = useAttrs()
const bindAttrs = computed(() => ({
class: attrs.class || '',
style: attrs.style || '',
}))
</script>
<template>
<Icon :icon="icon" v-bind="bindAttrs" />
</template>
4. 实战调用
xml
<template>
<!-- 知识库入口 -->
<SvgIcon icon="garden:knowledge-base-26" class="text-2xl flex-1" />
<!-- 带旋转动画 -->
<SvgIcon icon="mdi:loading" class="animate-spin text-xl" />
<!-- 行内按钮 -->
<button class="btn">
<SvgIcon icon="mdi:plus" /> 新建
</button>
</template>
5. 踩坑小抄
-
图标不显示?
检查图标名大小写 & 冒号:
mdi:home
✅Mdi:Home
❌ -
离线模式
生产内网无法访问
api.iconify.design
时,把所需图标提前打包:csspnpm i @iconify-json/mdi
然后在
main.js
注册:javascriptimport { addCollection } from '@iconify/vue' import mdi from '@iconify-json/mdi/icons.json' addCollection(mdi)
-
颜色/尺寸
Iconify 默认
width: 1em; height: 1em;
随字体走,直接改text-*
或text-2xl
即可。 -
SSR 白屏
Nuxt3 记得加
@iconify/vue
到build.transpile
。
6. 结语
现在新建 .vue
文件,我第一件事就是敲 <SvgIcon icon="" />
,图标焦虑彻底治好了。
如果你也有私藏图标小技巧,评论区互相种草,下次见 👋