- 安装包
vite-plugin-svg-icons
- 在main.ts中引入
import 'virtual:svg-icons-register';
- 在vite.config.ts中配置
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
const pathSrc = path.resolve(__dirname, 'src');
export default defineConfig({
plugins: [
createSvgIconsPlugin({
//指定要缓存的文件夹
iconDirs: [path.resolve(pathSrc, 'assets/svg')],
// 指定symbolId格式
symbolId: 'icon-[name]',
}),
]
});
- 创建 component 组件
<template>
<svg :class="svgClass" :width="width" :height="height">
<use :xlink:href="`#icon-${name}`" :fill="color"></use>
</svg>
</template>
<script setup lang="ts">
const props = withDefaults(
defineProps<{
svgClass?: string;
name: string;
color?: string;
width?: string;
height?: string;
}>(),
{
svgClass: 'svg-class',
color: '#fff',
width: '16px',
height: '16px',
}
);
</script>
- svg图标文件
svg代码
- 使用
import svgIcon from '@/components/svgIcon.vue';
<svgIcon name="xxx"></svgIcon>