SVG图标配置

使用 svg 后页面加载的不再是图片资源,这对页面性能来说是个很大的提升,而且 SVG 文件比img要小很多,放在项目中几乎不占用资源。


步骤 1:安装插件

安装 vite-plugin-svg-icons 插件以方便地管理和使用SVG图标:

1pnpm i vite-plugin-svg-icons -D

步骤 2:在 vite.config.ts 中配置插件

配置Vite插件,指定SVG图标的存放目录和如何生成SymbolId:

1import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
2import path from 'node:path'
3
4export default defineConfig({
5  plugins: [
6    createSvgIconsPlugin({
7      iconDirs:[path.resolve(process.cwd(), 'src/assets/icons')],
8      symbolId: 'icon-[dir]-[name]'
9    })
10  ],
11})

步骤 3:在 main.ts 中导入

导入 virtual:svg-icons-register 以注册SVG图标:

1import 'virtual:svg-icons-register'

步骤 4:使用SVG图标

在Vue模板中使用SVG图标,需要与use标签结合使用:

1<template>
2	<svg>
3    <use xlink:href="#icon-phone"></use>
4  </svg>
5</template>

use标签属性说明:

  • xlink:href:引入哪个图标,属性值必须是#icon-加上图标的名字。

  • fill:设置图标的颜色。

组件封装

步骤 1:组件封装

创建一个SVG图标组件 components/SvgIcon/index.vue

1<template>
2  <svg :style="{ width, height }">
3    <use :xlink:href="`${prefix}${name}`" :fill="color" />
4  </svg>
5</template>
6<script setup lang="ts">
7defineProps({
8  prefix: {
9    type: String,
10    default: "#icon-"
11  },
12  name: String,
13  color: {
14    type: String,
15    default: "#000"
16  },
17  width: {
18    type: String,
19    default: "16px"
20  },
21  height: {
22    type: String,
23    default: "16px"
24  }
25})
26</script>

步骤 2:对外暴露插件对象

components/index.ts 中对外暴露插件对象:

1import SvgIcon from './SvgIcon/index.vue'
2
3const allGlobalComponent = {SvgIcon}
4
5// 对外暴露的插件对象
6export default {
7  // 必须叫install,且会有app实例对象作为其参数
8  install(app) {
9    // 注册项目全部的全局组件
10    Object.keys(allGlobalComponent).forEach(key => {
11      app.component(key, allGlobalComponent[key])
12    })
13  }
14}

步骤 3:在 main.ts 注册全局组件

main.ts 中注册全局组件:

1// 引入自定义插件对象,注册整个项目的全局组件
2import globalComponent from '@/component'
3
4// 安装自定义插件
5// 注册时会执行 globalComponent 中的 install 方法
6app.use(globalComponent)