Vue3 集成 Font Awesome 图标库

Vue3 集成 Font Awesome 图标库

环境说明

项目基于 Element Plus Vite Starter 搭建。

依赖均指定了版本号,如需使用最新版请移除版本号。

安装 Font Awesome 图标库

核心组件

1
2
npm install @fortawesome/vue-fontawesome@3.1.2
npm install @fortawesome/fontawesome-svg-core@7.1.0

图标库

以免费图标库为例:regular、solid、brands

1
2
3
npm install @fortawesome/free-solid-svg-icons@7.1.0
npm install @fortawesome/free-regular-svg-icons@7.1.0
npm install @fortawesome/free-brands-svg-icons@7.1.0

配置 Font Awesome 图标库

按需引入

按需引入所需图标,按图标类型分类,分别添加到对应的数组中。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { library } from '@fortawesome/fontawesome-svg-core'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'

/**
 * 常规图标
 */
const regularIcons = []

/**
 * 实心图标
 */
const solidIcons = []

/**
 * 品牌图标
 */
const brandIcons = []

library.add(...regularIcons, ...solidIcons, ...brandIcons)

export function installFontAwesome(app: any) {
  app.component('font-awesome-icon', FontAwesomeIcon)
}

插件注册

main.ts 中注册 Font Awesome 图标库:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// ... 其他 import 语句
import { installFontAwesome } from './plugins/fontawesome'
// ... 其他 import 语句

// https://github.com/antfu/vite-ssg
export const createApp = ViteSSG(
  App,
  {
    routes,
    base: import.meta.env.BASE_URL,
  },
  (ctx) => {
    // install all modules under `modules/`
    Object.values(import.meta.glob<{ install: UserModule }>('./modules/*.ts', { eager: true }))
      .forEach(i => i.install?.(ctx))
    // ctx.app.use(Previewer)
    installFontAwesome(ctx.app)
  },
)

使用图标库

Font Awesome 搜索自己想要的图标,复制时选择 Vue - SVG Pkg。

fa-brands fa-github 图标为例:

添加图标到库中

将图标添加到对应的数组中:

 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
import { library } from '@fortawesome/fontawesome-svg-core'
import { faGithub } from '@fortawesome/free-brands-svg-icons'

import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'

/**
 * 常规图标
 */
const regularIcons = []

/**
 * 实心图标
 */
const solidIcons = []

/**
 * 品牌图标
 */
const brandIcons = [
    faGithub,
]

library.add(...regularIcons, ...solidIcons, ...brandIcons)

export function installFontAwesome(app: any) {
  app.component('font-awesome-icon', FontAwesomeIcon)
}

在组件中使用

1
2
3
4
5
<template>
  <div>
    <font-awesome-icon icon="fa-brands fa-github" />
  </div>
</template>

参考文档

如果本文对您有所帮助,欢迎打赏支持作者!

Licensed under CC BY-NC-SA 4.0
最后更新于 2025-11-21 09:34
使用 Hugo 构建
主题 StackJimmy 设计