SVG组件

SVG图标组件介绍与使用

这个组件是一个封装的 SVG 图标组件,用于统一加载 iconfont(通过 <use> 标签引用),支持传入图标名称、颜色、额外类名,适用于基于 iconfont.cn 等平台导出的 symbol 图标集。

<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName" :fill="color" />
  </svg>
</template>
​
<script lang="ts">
  import { defineComponent, computed } from 'vue'
​
  export default defineComponent({
    props: {
      iconClass: {
        type: String,
        required: true,
      },
      className: {
        type: String,
        default: '',
      },
      color: {
        type: String,
        default: '',
      },
    },
    setup(props) {
      return {
        iconName: computed(() => `#icon-${props.iconClass}`),
        svgClass: computed(() => {
          if (props.className) {
            return `svg-icon ${props.className}`
          }
          return 'svg-icon'
        }),
      }
    },
  })
</script>
​
<style scope lang="less">
  .nav-icon {
    position: relative;
    display: inline-block;
    margin-right: 12px;
    font-size: 15px;
  }
​
  .svg-icon {
    position: relative;
    width: 1em;
    height: 1em;
    vertical-align: -2px;
    fill: currentcolor;
  }
</style>

二、组件结构分析

template 模板部分
vue复制编辑<svg :class="svgClass" aria-hidden="true">
  <use :xlink:href="iconName" :fill="color" />
</svg>
说明:
  • 使用 <svg> 结合 <use> 标签,实现 SVG 图标的复用。

  • :xlink:href="iconName":绑定图标路径,如 #icon-home

  • :fill="color":支持自定义图标颜色。

  • :class="svgClass":支持额外类名传入,用于样式定制。

  • aria-hidden="true":屏蔽图标的可访问性(不被辅助工具识别为可交互元素)。

属性(props)说明:
Prop 名称类型是否必填说明
iconClassString图标的名称,如 home
classNameString额外添加的类名(样式扩展)
colorString图标颜色

setup() 返回:
  • iconName:返回 #icon-${iconClass},拼接 symbol id。

  • svgClass:返回一个 class 字符串,基础类名是 svg-icon,可追加自定义类名。

三、使用方式示例

在父组件中使用:
<svg-icon icon-class="home" class-name="custom-style" color="#42b983" />
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值