如何使用iconfont的svg

4,679 阅读1分钟

当你在开发vue项目时,组件库里面的icon图标满足不了你的需求时(或者经过UI设计的图标也可以导入到iconfont项目中,使用起来更方便),这时候就需要在项目中使用iconfont啦,比起unicode、font-class引用官方更推荐symbol, symbol是做了一个svg的集合

特点

  • 支持多色图标,不受单色限制
  • 支持像字体一样,通过css调整字样式
  • icon的字体使用的是字体渲染,在屏幕放大的情况下,会有锯齿不清晰,svg使用的是图形渲染则没有这种问题
  • 浏览器渲染svg的性能一般,不如png
  • 兼容性较差,支持ie9+及现代浏览器

使用步骤

  1. 在iconfont创建的项目中,点击Symbol,然后下载至本地,解压刚刚下载的压缩包把iconfont.js这个文件拷贝到项目中(其它文件不需要拷贝) 嘻嘻
  2. 在main.js中引入
import './assets/iconfont/symbols.js'
  1. 加入通用的css代码(只需要引入一次且必须要引入)
<style type="text/css">
  .icon {
     width: 1em; height: 1em;
     vertical-align: -0.15em;
     fill: currentColor;
     overflow: hidden;
  }
</style>
  1. 在页面中使用
<svg class="icon" aria-hidden="true">
    <use xlink:href="#icon-xxx"></use>	//icon-xxx为svg symbol的id,可在iconfont.js源码中查看,记得加上#号
</svg>

封装成组件

  1. 封装
<template>
  <i class="svg-icon">
    <svg class="icon" aria-hidden="true">
      <use :xlink:href="xlinkHref"></use>
    </svg>
  </i>
</template>

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

<style scoped lang="stylus" rel="stylesheet/stylus">
.svg-icon {
  .icon {
    width: 1em; height: 1em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
  }
}
</style>
  1. 在页面中使用
<svg-icon :symbolId='item.icon'></svg-icon>