手把手教你在Vue中使用阿里图标库IconFont

607 阅读1分钟

前言

还在为不会使用小图标而烦恼吗?

还在为项目需要使用定制化图标,非UI库图标而烦恼吗?

还在为Vue怎么封装一个Svg组件而烦恼吗?

不用着急,现在,它来了~~~

1、阿里图标库IconFont

image.png

  • 创建项目,输入名称即可,其他默认。

image.png

image.png

  • 新增图标,找一个喜欢的图标加入购物车,然后再购物车中添加至需要的项目。

image.png

image.png

  • 生成在线图标地址

image.png

  • 项目中使用,找到index.html文件,添加如下代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <base href="/" />
    <meta charset="UTF-8" />
    <title>Service One - 灵活扩展,随心定制</title>
    <script src="//at.alicdn.com/t/c/font_4221922_khutftyucm1.js"></script>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

2、SvgIcon组件

在Vue中封装一个SvgIcon组件,直接上代码。

// src/components/SvgIcon/SvgIcon.vue

<template>
  <svg
    class="svg-icon"
    :class="[$attrs.class, spin && 'svg-icon-spin']"
    :style="getStyle"
    aria-hidden="true"
  >
    <use :xlink:href="symbolId" />
  </svg>
</template>

<script lang="ts">
  import type { CSSProperties } from 'vue';
  import { defineComponent, computed } from 'vue';

  export default defineComponent({
    name: 'SvgIcon',
    props: {
      prefix: {
        type: String,
        default: 'icon',
      },
      name: {
        type: String,
        required: true,
      },
      size: {
        type: [Number, String],
        default: 16,
      },
      spin: {
        type: Boolean,
        default: false,
      },
    },
    setup(props) {
      const symbolId = computed(() => `#${props.prefix}-${props.name}`);

      const getStyle = computed((): CSSProperties => {
        const { size } = props;
        let s = `${size}`;
        s = `${s.replace('px', '')}px`;
        return {
          width: s,
          height: s,
        };
      });
      return { symbolId, getStyle };
    },
  });
</script>

<style lang="less" scoped>
  .svg-icon {
    display: inline-block;
    overflow: hidden;
    vertical-align: -0.15em;
    fill: currentcolor;
  }

  .svg-icon-spin {
    animation: loadingCircle 1s infinite linear;
  }
</style>

这里建议将SvgIcon组件全局注册, 具体根据项目实际情况而定。

import { createApp } from 'vue';
import SvgIcon from '@/components/SvgIcon/SvgIcon.vue'; 

const app = createApp(App);

//全局注册icon-svg 
app.component('SvgIcon', SvgIcon);

3、注意事项

本文只介绍了如何使用在线链接,当然通过下载图标添加至项目也是可以的。

其他信息,可以前往阿里巴巴矢量图标库文档了解。

4、结尾

完成上述步骤一和步骤二,即可在Vue项目使用阿里图标库IconFont。

当然,通过上述的方法,稍做改动也可以在Angular,React项目使用哟~

如有任何的问题,可以评论区留言哟~