使用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"
