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

关键要点

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值