[Vue3]自己封装Svg图标组件

12 篇文章 0 订阅

[Vue3]自己封装Svg组件

项目中引入iconfont

外链引用


symbol引用是一种全新的使用方式,应该说这才是未来的主流,也是平台目前推荐的用法。相关介绍可以参考这篇文章 这种用法其实是做了一个svg的集合,与其他两种相比具有如下特点:

  • 支持多色图标了,不再受单色限制。
  • 通过一些技巧,支持像字体那样,通过font-size,color来调整样式。
  • 兼容性较差,支持 ie9+,及现代浏览器。
  • 浏览器渲染svg的性能一般,还不如png

使用步骤如下:

第一步:拷贝项目下面生成的symbol代码:

//at.alicdn.com/t/font_8d5l8fzk5b87iudi.js

第二步:加入通用css代码(引入一次就行):

<style type="text/css">
    .icon {
       width: 1em; height: 1em;
       vertical-align: -0.15em;
       fill: currentColor;
       overflow: hidden;
    }
</style>

第三步:挑选相应图标并获取类名,应用于页面:

<svg class="icon" aria-hidden="true">
    <use xlink:href="#icon-xxx"></use>
</svg>

本地引用

如果是下载到本地,就在main.js里引入。

// 引入iconfont
import './assets/iconfont/iconfont.css';
import './assets/iconfont/iconfont.js';

img

然后这样就能用了

<svg class="icon" aria-hidden="true">
    <use xlink:href="#icon-xxx"></use>
</svg>

封装SvgIcon组件

svg文档:https://developer.mozilla.org/zh-CN/docs/Web/SVG

SvgIcon.vue

<template>
    <svg :class="classList" aria-hidden="true" @click="emit('click')">
        <!--        <use :xlink:href="iconName" :fill="color"/>-->
        <use :xlink:href="iconName" />
    </svg>
</template>
<script setup>
import { computed } from 'vue';

const emit = defineEmits(['click']);
const props = defineProps({
    className: {
        type: String,
        default: ''
    },
    iconClass: {
        type: String,
        required: true
    },
    color: {
        type: String,
        default: '#a94442'
    },
    size: {
        type: String,
        default: '20px'
    },

    // 是否允许点击
    clickable: {
        type: Boolean,
        default: true
    }
});
const classList = computed(() => {
    const res = ['icon', props.className || ''];

    if (props.clickable) {
        res.push('clickable');
    }
    return res;
});
const iconName = computed(() => {
    return `#${props.iconClass}`;
});
</script>
<style lang="less" scoped>
.icon {
    /* v-bind是Vue3才支持的功能,可以将CSS的值与js的值绑定 */
    width: v-bind('props.size');
    height: v-bind('props.size');
    position: relative;
    vertical-align: -2px;
    fill: currentColor;
    font-weight: 700;
    color: #a94442;
}

.clickable {
    cursor: pointer;

    &:hover {
        //border: 1px solid rgba(0, 0, 0, 0);
        color: #66b1ff;
    }
}
</style>

这样就将iconfont封装成了svg来调用了,这里我们重点说几个属性:

  • aria-hidden:默认为false,设置为true表示会把整个元素包括子元素从可访问树(AOM)上移除,但是在DOM树上还是存在的

  • xlink:hrefuse元素的属性

  • v-bind:Vue3的特性,可用于关联CSS和js

  • fill:如果在动画接收还需要保持动画的值,可用于设置颜色

  • clickable:图标是否是可以点击的

使用SvgIcon组件

<SvgIcon
         style="margin-left: 10px"
         icon-class="icon-shuaxin"
         @click="handleTestCaseRefresh"
></SvgIcon>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值