zhongshujie
3 天以前 d41648827f2d21c7884ac8d00e8d8a9ac1cd2715
src/components/svgIcon/index.vue
@@ -1,9 +1,9 @@
<template>
  <!-- 如果是 Element UI 图标,保持不变 -->
  <i v-if="iconFileName.indexOf('el-icon-') === 0" :class="iconFileName" />
  <!-- 如果是 SVG 图标,进行改造 -->
  <svg v-else class="svg-icon" aria-hidden="true" v-on="$listeners" :style="svgStyle">
  <svg v-else class="svg-icon" aria-hidden="true" v-on="$listeners" >
    <!-- 
      :xlink:href 动态绑定图标ID
      注意:这里假设你的图标ID是 "icon-" + iconFileName
@@ -20,39 +20,13 @@
      type: String,
      required: true
    },
    // 新增一个 color prop,用于接收颜色
    color: {
      type: String,
      // 默认值设为 'inherit',它会继承父元素的文字颜色
      default: 'inherit'
    },
    // 可选:增加尺寸控制
    size: {
      type: String,
      default: '1em'
    }
  },
  computed: {
    // 使用计算属性来动态生成样式
    svgStyle() {
      return {
        // 关键点:将传入的 color 值赋给 CSS 的 'color' 属性
        color: this.color,
        // 关键点:设置图标尺寸
        fontSize: this.size,
        // 如果需要,也可以在这里设置宽高,但用 font-size 更灵活
        // width: this.size,
        // height: this.size,
      };
    }
  }
}
</script>
<style scoped>
.svg-icon {
  /* 
    核心魔法!
    1. width 和 height 使用 em 单位,使其与 font-size 关联。
    2. overflow: hidden 防止图标在某些情况下溢出。
    3. vertical-align: 调整图标与文字的对齐基线。
@@ -63,6 +37,7 @@
  height: 1em;
  overflow: hidden;
  vertical-align: -0.15em;
  fill: currentColor;
  fill: currentColor;
}
</style>