前言
本文讲的是使用uni-app开发微信小程序时,如何使用iconfont的解决方案
前置知识
1). 什么是IconFont?
顾名思义,IconFont 就是字体图标。 严格地说,就是一种字体,但是,它们不包含字母或数字,而是包含符号和字形。 您可以使用CSS 设置样式,就像设置常规文本一样,这使得IconFont 成为Web 开发时图标的热门选择。
2). 什么是uni-app?
uni-app 是一个使用 Vue.js 开发所有前端应用的框架,开发者编写一套代码,可发布到iOS、Android、H5、以及各种小程序(微信/支付宝/百度/头条/QQ/钉钉/淘宝)、快应用等多个平台。
准备工作
开始表演
下载字体库
如下图所示,打开 iconfont 官网,通过「图标管理」-> 「我的项目」-> 「我参与的项目」-> 「下载至本地」,
将iconfont项目中的字体库下载到本地。将字体库转换为base64
打开 base64 encoder 网址,解压上一步骤下载的文件,选择其中的字体文件iconfont.ttf
,如下图所示:新建一个iconfont.css文件
在css中引入对应的iconfont,并将第1步骤下载的iconfont.css
中的字体图标类定义代码
粘贴过来。
1 | @font-face { |
2 | font-family: 'ym-iconfont'; |
3 | font-weight: normal; |
4 | font-style: normal; |
5 | src: url(data:font/truetype;charset=utf-8;base64,第2个步骤获得的base64数据) format('truetype'); |
6 | } |
7 | .ym-iconfont { |
8 | font-family: 'ym-iconfont' ; |
9 | font-style: normal; |
10 | -webkit-font-smoothing: antialiased; |
11 | -moz-osx-font-smoothing: grayscale; |
12 | } |
13 | .icon-share-link:before { |
14 | content: "\e631"; |
15 | } |
16 | .icon-rate-fill:before { |
17 | content: "\e6ca"; |
18 | } |
封装一个Icon组件,代码如下:
1
<template>
2
<text class="ym-iconfont"
3
:class="[iconName]"
4
/>
5
</template>
6
7
<script>
8
export default {
9
name: 'YmIcon',
10
props: {
11
name: {
12
type: String,
13
required: true
14
}
15
},
16
computed: {
17
iconName() {
18
return `icon-${this.name}`
19
}
20
},
21
methods: {
22
handleClick(event) {
23
this.$emit('click', event)
24
}
25
}
26
}
27
</script>
28
29
<style lang="less" scoped>
30
@import '../../static/styles/iconfont.css';
31
.ym {
32
&-iconfont {
33
display: inline-block;
34
box-sizing: border-box;
35
width: 1em;
36
height: 1em;
37
overflow: hidden;
38
line-height: 1;
39
vertical-align: -0.15em;
40
}
41
}
42
</style>
使用
iconfont
,推荐全局引用icon组件,字体图标大小用font-size
定义,颜色用color
定义。代码如下:
1 | <template> |
2 | <ym-icon class="share-icon" |
3 | name="icon-share-link" |
4 | /> |
5 | <ym-icon class="rate-fill-icon" |
6 | name="icon-rate-fill" |
7 | /> |
8 | </template> |
9 | <style lang="less" scoped> |
10 | .share-icon { |
11 | font-size: 10px; |
12 | color: #666; |
13 | } |
14 | </style> |
以上,关于在uni-app中使用iconfont的说明,有更好方案欢迎一起讨论改进。