方式一:原生导入 SVG 内容(可改色、无插件)
步骤 1:准备 SVG
把你的图标放到:src/assets/icons/home.svg
步骤 2:直接导入 SVG 源码
利用 Vite 原生的 ?raw 导入 SVG 字符串,再用 v-html 渲染。
<template>
<!-- 渲染 SVG -->
<div v-html="home" class="icon-wrapper"></div>
</template>
<script setup>
// 原生导入 SVG 源码(关键:加 ?raw)
import homefrom '@/assets/icons/home.svg?raw'
</script>
<style scoped>
/* 修改颜色(必须去掉 SVG 内部的 fill) */
.icon-wrapper :deep(svg) {
fill: #ff4d4f; /* 红色 */
width: 100%;
height: 100%;
}
</style>
方式二:封装成全局组件
步骤 1:创建组件:src/components/SvgIcon.vue
<template>
<div class="svg-icon" v-html="svgContent"></div>
</template>
<script setup>
import { computed } from 'vue'
const props = defineProps({
name: {
type: String,
required: true
}
})
// 自动根据 name 导入 SVG
const svgContent = computed(() => {
// 关键:原生导入
return import.meta.glob('@/assets/icons/*.svg', { eager: true, as: 'raw' })[
`/src/assets/icons/${props.name}.svg`
]
})
</script>
<style scoped>
</style>
步骤 2. 任意页面直接用
<template>
<SvgIcon name="home" class="icon-wrapper"/>
</template>
<script setup>
import SvgIcon from '@/components/SvgIcon.vue'
</script>
<script setup>
.icon-wrapper{
fill: #ffffff;
}
.icon-wrapper:hover{
fill:#FDB2CB;
}
</script>