svg use渲染问题?

有以下的svg图片

<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none">
  <circle cx="10" cy="10" r="8" stroke="#00A870" stroke-width="1.2"/>
  <path d="M6 10.1111L8.66667 12.7778L14 7" stroke="#00A870" stroke-width="1.2"/>
</svg>

在vscode中预览的时候颜色是正常的,如下
image.png
但使用封装的图标组件、

<template>
  <svg
    aria-hidden="true"
    :class="`${svgClass} focus:outline-none svg-icon`"
    :width="`${width}`"
    :height="`${height}`"
  >
    <use v-bind="{ 'xlink:href': `#${computedSvgName}`}" />
  </svg>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import VueTypes from 'vue-types'
import ids from 'virtual:svg-icons-names'

export default defineComponent({
  name: 'Icon',
  props: {
    svgName: VueTypes.string.def('').isRequired,
    svgClass: VueTypes.string.def(''),
    width: VueTypes.oneOfType([VueTypes.number, VueTypes.string]).def(24),
    height: VueTypes.oneOfType([VueTypes.number, VueTypes.string]).def(24)
  },
  setup (props) {
    const computedSvgName = computed(() => {
      return ids.find((el) => el.match(/_([\w-]+)$/)[1] === props.svgName)
    })
    return {
      computedSvgName
    }
  }
})
</script>

<style lang="scss" scoped>
.svg-icon {
  @apply inline-block;
}
</style>

在项目中引入调用之后,发现外层的circle无论如何都会是灰色
image.png
但将该svg作为background的话,不会有此问题

阅读 163
avatarAI BotBETA

可能的原因是被引用的 SVG 符号(symbol)丢失了内联样式属性。当使用 <use> 元素引用 SVG 符号时,需要注意:

  1. 内联样式优先级:被引用的符号需要直接在元素上声明样式属性(如 stroke、fill),使用 CSS 类名可能无法生效
  2. 符号定义方式:检查 SVG 符号的定义是否类似这样(需要保留内联属性):

    <symbol id="icon" viewBox="0 0 20 20" fill="none" stroke="#00A870">
      <circle cx="10" cy="10" r="8" stroke-width="1.2"/>
      <path d="M6 10.1111L8.66667 12.7778L14 7" stroke-width="1.2"/>
    </symbol>
  3. 颜色继承问题:可以尝试在父级 SVG 中强制设置颜色:

    <svg :style="{ stroke: '#00A870' }">
      <use .../>
    </svg>
  4. 雪碧图工具配置:如果是通过构建工具(如 vite-svg-loader)生成 SVG 符号,需要确保配置保留了属性:

    // vite.config.js
    export default {
      plugins: [
     svgLoader({
       svgoConfig: {
         plugins: [{ name: 'removeAttrs', params: { attrs: '(fill|stroke)' } }]
       }
     })
      ]
    }

建议先检查生成的 SVG 符号定义是否包含内联的 stroke 属性。如果已被移除,需要调整 SVG 处理工具的配置来保留这些属性。

1 个回答
<svg xmlns="http://www.w3.org/2000/svg"  viewBox="0 0 20 20">
  <circle cx="10" cy="10" r="8" stroke="currentColor" stroke-width="1.2"/>
  <path d="M6 10.1111L8.66667 12.7778L14 7" stroke="currentColor" stroke-width="1.2"/>
</svg>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏