Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

通过IconFont实现过程看如何在VUE中动态加载IconFont图标 #19

Open
rico-c opened this issue Jan 4, 2019 · 0 comments
Open
Labels

Comments

@rico-c
Copy link
Owner

rico-c commented Jan 4, 2019

原理

首先引用一下阿里iconfont官网的使用介绍:

unicode是字体在网页端最原始的应用方式,特点是:

  • 兼容性最好,支持ie6+,及所有现代浏览器。
  • 支持按字体的方式去动态调整图标大小,颜色等等。
  • 但是因为是字体,所以不支持多色。只能使用平台里单色的图标,就算项目里有多色图标也会自动去色。

unicode使用步骤如下:

第一步:拷贝项目下面生成的font-face
@font-face {font-family: 'iconfont';
    src: url('iconfont.eot');
    src: url('iconfont.eot?#iefix') format('embedded-opentype'),
    url('iconfont.woff') format('woff'),
    url('iconfont.ttf') format('truetype'),
    url('iconfont.svg#iconfont') format('svg');
}
第二步:定义使用iconfont的样式
.iconfont{
    font-family:"iconfont" !important;
    font-size:16px;font-style:normal;
    -webkit-font-smoothing: antialiased;
    -webkit-text-stroke-width: 0.2px;
    -moz-osx-font-smoothing: grayscale;}
第三步:挑选相应图标并获取字体编码,应用于页面
<i class="iconfont">&#x33;</i>

可以看到使用unicode方法iconfont需要主要操作

  1. 引入字体
  2. 在标签中使用

但是为什么引入了iconfont的字体后,在标签内直接输入一段编码就可以显示成图标呢?

这里我们可以看一个例子:

<p>Hello &#119;&#111;&#114;&#108;&#100;</p>

p{
  font-family: Helvetica Neue
}  

这里&#119;&#111;&#114;&#108;&#100;实际上是'world'的Unicode编码,当我们在HTML文件中直接写入Unicode编码后,并用浏览器打开后,可以看到浏览器将上面的p标签渲染成'Hello world'。

这是因为浏览器在解析HTML文件时,读到Hello,会先将该字符串转为对应的Unicode编码,随后向该标签所属的字体文件查询对应的Unicode编码的对应的字体,然后再在浏览器上渲染出来,如果是Unicode编码则直接向字体文件查询对应的字体,所以我们可以看到Unicode编码和直接输入字母或汉字渲染效果相同。

所以当我们引入了定义好的iconfont图标字体,只要通过在HTML中写入Unicode就可以渲染出对应的图标。

在VUE中动态渲染iconfont

在如下代码中,如果我们直接使用VUE的花括号来动态加载UnicodeIconFont的话会发现并不能动态的渲染,只能在网页上渲染出Unicode的代码,而不能渲染出图标。

代码如下:

jietu20190104-181726

这是因为花括号和v-text相同,默认输出文本,而文本更新不会触发浏览器的HTML解析。

这时我们可以通过使用v-html来向标签动态的加载HTML元素,这是就会触发浏览器的HTML解析功能,图标就可以顺利的渲染出来了。

jietu20190104-181706

@rico-c rico-c added the 笔记 label Jan 4, 2019
@rico-c rico-c changed the title 通过IconFont原理看如何在VUE中动态加载IconFont图标 通过IconFont实现过程看如何在VUE中动态加载IconFont图标 Jan 5, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant