- SvgIcon.vue 组件
<template>
<svg
:class="['svg-icon', className]"
:style="svgStyle"
:width="size"
:height="size"
aria-hidden="true"
>
<use :href="symbolId" />
</svg>
</template>
<script setup lang="ts">
import { computed } from 'vue'
interface Props {
name: string
size?: string | number
className?: string
color?: string
rotate?: number
spin?: boolean
prefix?: string
}
const props = withDefaults(defineProps<Props>(), {
size: '1em',
className: '',
color: 'currentColor',
rotate: 0,
spin: false,
prefix: '#icon-'
})
const symbolId = computed(() => props.prefix + props.name)
const svgStyle = computed(() => ({
fill: props.color,
transform: props.rotate ? `rotate(${props.rotate}deg)` : '',
animation: props.spin ? 'rotating 1s linear infinite' : ''
}))
</script>
<style>
.svg-icon {
display: inline-block;
vertical-align: middle;
overflow: hidden;
fill: currentColor;
}
symbol {
color: v-bind(color);
}
@keyframes rotating {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
</style>
- 安装插件 pnpm add -D vite-plugin-svg-icons
- 配置 vite
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default defineConfig({
plugins: [
createSvgIconsPlugin({
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
symbolId: 'icon-[dir]-[name]',
}),
],
})
- 使用示例
<template>
<SvgIcon name="user" size="24" color="#333" />
</template>
- 注意:
设置 color 无法修改 svg 颜色问题
通常是因为 SVG 文件本身定义了 fill 属性
- 移除 SVG 源文件中的固定颜色属性:
<svg>
<path fill="#000000" d="..."/>
</svg>
<svg>
<path d="..."/>
</svg>
- 或者在 SVG 源文件中使用
currentColor
:
<svg>
<path fill="currentColor" d="..."/>
</svg>