1-安装
npm i vite-plugin-svg-icons -D
2-配置
vite.config.js中编辑
import { fileURLToPath, URL } from 'node:url'
import {createSvgIconsPlugin} from 'vite-plugin-svg-icons';
// 在plugins增加 createSvgIconsPlugin插件
export default defineConfig({
plugins: [
createSvgIconsPlugin({
iconDirs: [fileURLToPath(new URL('./src/assets/svgs', import.meta.url))],
symbolId: 'icon-[dir]-[name]',
})
]
})
3-引入
在src/main.ts进行全局引入
import 'virtual:svg-icons-register'
4-具体实现:
增加SVG组件
在src/components
目录下新增文件夹SvgIcon
,并在该目录下新增文件index.vue
,代码如下:
<!-- SVG图标 -->
<script setup lang="ts">
import {computed} from 'vue';
import {useSystemStore} from '@/store/system';
const props = defineProps({
prefix: {
type: String,
default: 'icon'
},
name: {
type: String,
required: true
},
color: {
type: String,
required: true,
default:'#fc4a14'
}
});
const symbolId = computed(() => `#${props.prefix}-${props.name}`);
</script>
<template>
<!-- 有时修改颜色不成功得到的经验:修改svg颜色,需要去内部svg文件中比如login_username.svg中删除掉fill样式才生效 目前这些svg都是定义在class 比如.cls-2{fill:**}把样式删除即可 -->
<svg aria-hidden="true">
<use :xlink:href="symbolId" :fill="color" />
</svg>
</template>
全局组件挂载 (main.ts)
import SvgIcon from '@/components/SvgIcon/index.vue';
app.component('SvgIcon', SvgIcon);
添加Typescript支持
在tsconfig.app.json进行设置
{
"compilerOptions": {
"types": ["vite-plugin-svg-icons/client"]
}
}
具体使用
1-从UI那里拿到svg文件存放在src/assets/svgs
下,并命名,比如命名为username.svg
;
2-具体使用参考:
<template>
<div class="w-full h-full flex flex-col justify-start items-start">
<!-- name参数这里填写图标文件名不需要加上svg -->
<SvgIcon name="username" class="w-[24px] h-[24px] object-scale-down text-amber-500"/>
</div>
</template>