在线使用 有时候会因网络问题影响用户体验;直接放在 本地使用 ,如果过多使用也会显得繁琐,所以就可以将其封装成一个组件,也方便维护。?
封装基于阿里巴巴图标库的项目图标。
准备
将项目内的图标下载至本地
在了路径 src/assets 下新建文件夹 iconfont ,用来存放字体图标的本地文件
解压下载到本地的字体图标文件,放到 iconfont 文件夹下
如过项目中没有下载 css-loader 依赖包,就进行下载,否则会报错
npm install css-loader -D
封装
unicode引用封装
<template>
<div>
<span class="iconfont" v-html="name"></span>
<slot></slot>
</div>
</template>
<script>
export default {
name: 'iconUnicode',
props: {
name: {
type: String,
required: true
}
}
}
</script>
<style scoped>
@font-face {
/* Unicode */
font-family: "iconfont";
src: url("assets/iconfont/iconfont.eot");
src: url("assets/iconfont/iconfont.eot?#iefix") format("embedded-opentype"),
url("assets/iconfont/iconfont.woff2") format("woff2"),
url("assets/iconfont/iconfont.woff") format("woff"),
url("assets/iconfont/iconfont.ttf") format("truetype"),
url("assets/iconfont/iconfont.svg#iconfont") format("svg");
}
.iconfont {
font-family: "iconfont" !important;
font-size: 2em;
font-style: normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
</style>
font-class引用封装
<template> ? <div> ? ? <span class="iconfont" :class="iconTag"></span> ? ? <slot></slot> ? </div> </template>
<script>
import "assets/iconfont/iconfont.css";
export default {
? name: "iconFontClass",
? props: {
? ? name: {
? ? ? type: String,
? ? ? required: true
? ? }
? },
? computed: {
? ? iconTag() {
? ? ? return `icon-${this.name}`;
? ? }
? }
};
</script>
<style scoped>
.iconfont {
? font-family: "iconfont" !important;
? font-size: 2em;
? font-style: normal;
? -webkit-font-smoothing: antialiased;
? -moz-osx-font-smoothing: grayscale;
}
</style>
symbol引用封装
<template> ? <div> ? ? <svg class="icon" aria-hidden="true"> ? ? ? <use :xlink:href="iconTag" rel="external nofollow" ></use> ? ? </svg> ? ? <slot></slot> ? </div> </template>
<script>
import "assets/iconfont/iconfont.js";
export default {
? name: "iconSymbol",
? props: {
? ? name: {
? ? ? type: String,
? ? ? required: true
? ? }
? },
? computed: {
? ? iconTag() {
? ? ? return `#icon-${this.name}`;
? ? }
? }
};
</script>
<style scoped>
.icon {
? width: 2em;
? height: 2em;
? vertical-align: -0.15em;
? fill: currentColor;
? overflow: hidden;
}
</style>
引入
全局引入
// main.js
// 引入并注册全局组件
import iconUnicode from './ui/iconUnicode'
Vue测试数据ponent('iUnicode', iconUnicode)
局部引入
// 局部引入并使用
import iSymbol from "ui/iconSymbol"
import iFont from "ui/iconFontClass"
export default {
//注册
components: {
iSymbol,
iFont
}
};
使用
<template>
<div class="box">
<i-symbol name="fanhuidingbu">Symbol</i-symbol>
<i-font name="fanhuidingbu">Font class</i-font>
<i-unicode name="" style="font-size:30px;color:#333">Unicode</i-unicode>
</div>
</template>
效果图:
最后
也可以通过在线链接进行封装,但不管是在线使用还是本地使用,每次在项目中添加新图标之后都要更新一下 本地iconfont文件 或者 在线链接 。
demo 已上传 GitHub
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
查看更多关于vue中手动封装iconfont组件解析(三种引用方式的封装和使用)的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did121032