这篇文章主要介绍了iconfont的三种使用方式,需要的朋友可以参考下
在我们项目中经常要使用到iconfont,在此我们使用阿里巴巴矢量库提供的icon图标,此图标库足够为我们提供大量的图标,我们首先需要的事在阿里巴巴矢量图标库新建一个自己的账号,并且新建一个项目,这个项目包含了你所有要用到的图标。我们需要选中需要的图标放到自己的项目中,并下载下来放到自己项目下的iconfont文件夹之下。(需要更新图标时,下载包也需要重新下载更新)
方式一:使用symbol方式(本质是用svg标签构成的)
第一步:为了代码更好的复用,我们封装一个svg-icon组件,代码如下:
<template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="iconName" rel="external nofollow" ></use>
</svg>
</template>
<script>
export default {
name: 'svg-icon',
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String
}
},
computed: {
iconName() {
return `#icon-${this.iconClass}` // 注意:因为此处绑定的svgClass名已经包含#icon,所以复制symbol名字事不需要名字的前缀了
},
svgClass() {
if (this.className) {
return 'svg-icon ' + this.className
} else {
return 'svg-icon'
}
}
}
}
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
第二步:在main.js中引入
<template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="iconName" rel="external nofollow" ></use>
</svg>
</template>
<script>
export default {
name: 'svg-icon',
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String
}
},
computed: {
iconName() {
return `#icon-${this.iconClass}` // 注意:因为此处绑定的svgClass名已经包含#icon,所以复制symbol名字事不需要名字的前缀了
},
svgClass() {
if (this.className) {
return 'svg-icon ' + this.className
} else {
return 'svg-icon'
}
}
}
}
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
第三步:使用
在自己需要用到的组件中:
<template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="iconName" rel="external nofollow" ></use>
</svg>
</template>
<script>
export default {
name: 'svg-icon',
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String
}
},
computed: {
iconName() {
return `#icon-${this.iconClass}` // 注意:因为此处绑定的svgClass名已经包含#icon,所以复制symbol名字事不需要名字的前缀了
},
svgClass() {
if (this.className) {
return 'svg-icon ' + this.className
} else {
return 'svg-icon'
}
}
}
}
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
另外两种使用方式是使用unicode和fontclass方式,如上面的代码所示引入与使用 友情链接批量查询
然后我们谈谈这三种方式的优缺点吧
unicode:
优点:
- 兼容性最好,支持ie6+
- 支持按字体的方式去动态调整图标大小,颜色等等
缺点:
- 不支持多色图标
- 在不同的设备浏览器字体的渲染会略有差别,在不同的浏览器或系统中对文字的渲染不同,其显示的位置和大小可能会受到font-size、line-height、word-spacing等CSS属性的影响,而且这种影响调整起来较为困难
- 不直观,看unicode码很难分辨什么图标
fontclass:
- 兼容性良好,支持ie8+
- 相比于unicode语意明确,书写更直观。可以很容易分辨这个icon是什么。
symbol:
- 支持多色图标了,不再受单色限制。
- 支持像字体那样通过font-size,color来调整样式。
- 支持 ie9+
- 可利用CSS实现动画。
- 减少HTTP请求。
- 矢量,缩放不失真
- 可以很精细的控制SVG图标的每一部分
综上所述的一些特点,个人比较推荐使用symbol或者fontclass的方式