vue3 项目中优雅的使用 SVG 图标(vite-plugin-svg-icons)
1、背景
vite-plugin-svg-icons
是一个用于 Vite 构建工具的插件,它可以帮助开发者轻松地在 Vue 项目中使用 SVG 图标。该插件的主要功能包括:
-
SVG 图标自动导入:将指定目录下的 SVG 图标自动导入为 Vue 组件
-
性能优化:通过预加载和缓存机制提高图标加载性能
-
按需加载:只打包实际使用的图标,减小最终构建体积
-
样式自定义:支持通过 CSS 自定义图标颜色和大小
2、Vue 3 使用教程
1、安装插件
npm install vite-plugin-svg-icons -D
2、配置 Vite
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { createSvgIconsPlugin } from 'vite-plugin-svg-icons' import path from 'path' export default defineConfig({ plugins: [ vue(), createSvgIconsPlugin({ // 指定图标文件夹路径 iconDirs: [path.resolve(process.cwd(), 'src/icons')], // 指定 symbolId 格式 symbolId: 'icon-[dir]-[name]', }) ] })
3、创建 SVG 图标目录
在 src
目录下创建 icons
文件夹,并添加一些 SVG 文件,例如:
-
src/icons/home.svg
-
src/icons/user.svg
-
src/icons/arrow-left.svg
4、注册 SVG 组件
在 main.js
中添加以下代码:
import { createApp } from 'vue' import App from './App.vue'
import svgIcon from './components/svg-icon';
let instance = createApp(App);
instance.use(svgIcon);
instance.mount('#app')
5、创建 SVG 图标组件
在components/svg-icon下创建SvgIcon.vue
<template>
<svg aria-hidden="true" :class="className" :width="width" :height="height" >
<use :xlink:href="symbolId" />
</svg>
</template>
<script setup>
import { computed } from 'vue'
const props = defineProps({
name: {
type: String,
required: true
},
className: {
type: String,
default: ''
},
width: {
type: Number,
default: 16
},
height: {
type: Number,
default: 16
},
})
const symbolId = computed(() => `#icon-${props.name}`)
</script>
6、全局安装SvgIcon.vue组件
在components/svg-icon下创建index.ts
import { type App } from 'vue'; import SvgIcon from './SvgIcon.vue'; import 'virtual:svg-icons-register'; /** * Svg图标插件 */ export default { install: (app: App): void => { app.component('svg-icon', SvgIcon); }, };
7、使用 SVG 图标
<template> <div class="container"> <h1>SVG 图标使用示例</h1> <div class="icon-grid"> <div class="icon-item"> <svg-icon name="home" class="icon" /> <span>首页</span> </div> <div class="icon-item"> <svg-icon name="user" class="icon" /> <span>用户</span> </div> <div class="icon-item"> <svg-icon name="arrow-left" class="icon" /> <span>返回</span> </div> </div> </div> </template> <script setup> </script> <style> .container { max-width: 800px; margin: 0 auto; padding: 2rem; text-align: center; } .icon-grid { display: flex; justify-content: center; gap: 2rem; margin-top: 2rem; } .icon-item { display: flex; flex-direction: column; align-items: center; gap: 0.5rem; } .icon { width: 2rem; height: 2rem; fill: currentColor; // 继承父级颜色 } .icon:hover { color: #42b883; /* 修改icon的颜色Vue 绿色 */ } </style>