使用svg图标

方式一:原生导入 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>

关键要点

必须加?raw 作用:告诉 Vite 直接导入 SVG 文本内容,不转成图片。

能改色的前提打开你的 .svg 文件,删除所有 fill="xxx"

相关推荐
古茗前端团队1 小时前
急招!前端|测试|后端|产品(名额多,速来)
前端·后端·架构
Lsx_2 小时前
不只是 Prompt:用 Superpowers Skill 给 AI 编程装上工程化工作流
前端·ai编程·claude
小碗细面2 小时前
前端 Prompt 工程实战:如何搭建场景化 Prompt 库
前端·ai编程
阿瑞IT2 小时前
2026年 AI Agent 生产化落地全景:四大高频故障根因分析与工程解法
前端
木木剑光2 小时前
我开源了一个 React 组件库,沉淀了多个高频组件和实用 Hooks
前端·javascript·react.js
kyriewen2 小时前
DeepSeek API 高峰时段涨价 2 倍,便宜大碗的时代要结束了?
前端·ai编程·deepseek
Moment3 小时前
牛逼,NextJs 从 16.3 开始全面拥抱 Agent Native 🥰🥰🥰
前端·后端·面试
沸点小助手3 小时前
6月沸点活动获奖名单公示|本周互动话题上新🎊
前端·后端
Csvn3 小时前
React 19 `use()` 来了:以后数据加载可以不用 useEffect?
前端·react.js
没落英雄3 小时前
从零开始搭建一个 AI Agent —— LangChain + TypeScript 实战手记
前端·人工智能·架构