使用 iconfont 中的 svg 图标

最近在使用 Element-UI开发的时候发现其图标并不是够用,于是想着如何将 https://www.iconfont.cn/home/index 上面的图标导入进自己的项目中去。

网上的搜索结果基本都是传统的引入CSS的方法,并没有使用到SVG的特性,这里介绍使用SVG来引入图标,这中方式普适任意的组件库。

首先我们在iconfont上新键好自己的项目并下载至本地,打开之后其文件如下

使用 iconfont 中的 svg 图标_第1张图片
我们只使用其中的iconfont.js,然后将其引入到我们的项目中去

import 'PATH/iconfont.js';

我们可以看一下iconfont.js源码,其大致是将一个SVG的图标集写到了源码中去,运行后我们可以看到这段SVG集合
使用 iconfont 中的 svg 图标_第2张图片
每一个图标项的ID是我们原先自己设置好的,接下来我们只要在项目中引用这个ID即可,如下

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

添加CSS养生

  .icon {
    width: 1em;
    height: 1em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
  }

以上就完成了在我们项目中使用SVG图标,我们就可以随意改变图标的颜色和大小啦!

接下来我们将其封装成一个VUE组件库

<template>
  <i class="sketch-icon">
    <svg class="icon svgfont" aria-hidden="true">
      <use :xlink:href="xlinkHref"></use>
    </svg>
  </i>
</template>

<script>
export default {
  name  : 'SketchIcon',
  props : {
    type : {
      type     : String,
      required : true,
    },
  },
  computed : {
    xlinkHref() {
      return `#${this.type}`;
    },
  },
};
</script>

<style scoped lang="less">
.sketch-icon {
  .icon {
    width: 1em;
    height: 1em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
  }
}
</style>

使用方式

    <sketch-icon type="sk-sound"/>

最后注意,如果你的项目使用了 eslint 的话,请将其加到.eslintignore文件中去,防止eslint的检测导致的控制台大量输出。

PATH/iconfont.js

欢迎关注微信公众号,会有最新的文章哦~: 子曰思鱼
在这里插入图片描述

你可能感兴趣的:(前端Vue,iconfont,Vue,svg)