一、首先登陆阿里云矢量图标库,把需要的字体图标加入到自己的项目中
二、阿里云图标的四种方式(推荐第三种方式引入,如果不考虑网络问题可以用在线引入的方式)
进入项目以后会看到阿里云可以选择三种方式进行导入图标,选中图标后点击下载至本地。
下载到本地,解压以后的文件夹列表如下:
选中iconfont.js文件
在项目中创建如下目录及文件
iconfont.js就是上上面目录中复制的文件
两种引用方法
第一种通过.svg文件方法引入
index.js内容如下
/**
* 字体图标, 统一使用SVG Sprite矢量图标(http://www.iconfont.cn/)
*
* 使用:
* 1. 在阿里矢量图标站创建一个项目, 并添加图标(这一步非必须, 创建方便项目图标管理)
* 2-1. 添加icon, 选中新增的icon图标, 复制代码 -> 下载 -> SVG下载 -> 粘贴代码(重命名)
* 2-2. 添加icons, 下载图标库对应[iconfont.js]文件, 替换项目[./iconfont.js]文件
* 3. 组件模版中使用 [<icon-svg name="canyin"></icon-svg>]
*
* 注意:
* 1. 通过2-2 添加icons, getNameList方法无法返回对应数据
*/
import Vue from 'vue'
import IconSvg from '@/components/icon-svg'
import './iconfont.js'
Vue.component('IconSvg', IconSvg)
const svgFiles = require.context('./svg', true, /\.svg$/)
const iconList = svgFiles.keys().map(item => svgFiles(item))
export default {
// 获取图标icon-(*).svg名称列表, 例如[shouye, xitong, zhedie, ...]
getNameList () {
return iconList.map(item => item.default.id.split('-')[1])
}
}
第二种方法是通过iconfont.js文件引入,index.js文件如下
/**
* 字体图标, 统一使用SVG Sprite矢量图标(http://www.iconfont.cn/)
*
* 使用:
* 1. 在阿里矢量图标站创建一个项目, 并添加图标(这一步非必须, 创建方便项目图标管理)
* 2-1. 添加icon, 选中新增的icon图标, 复制代码 -> 下载 -> SVG下载 -> 粘贴代码(重命名)
* 2-2. 添加icons, 下载图标库对应[iconfont.js]文件, 替换项目[./iconfont.js]文件
* 3. 组件模版中使用 [<icon-svg name="canyin"></icon-svg>]
*
* 注意:
* 1. 通过2-2 添加icons, getNameList方法无法返回对应数据
*/
import Vue from 'vue'
import IconSvg from '@/components/icon-svg'
import './iconfont.js'
Vue.component('IconSvg', IconSvg)
iconfont.js文件就是上面的iconfont.js文件,
两种也可同时使用
import IconSvg from '@/components/icon-svg’是引入的图标的封装组件
<template>
<svg
:class="getClassName"
:width="width"
:height="height"
aria-hidden="true">
<use :xlink:href="getName"></use>
</svg>
</template>
<script>
export default {
name: 'icon-svg',
props: {
name: {
type: String,
required: true
},
className: {
type: String
},
width: {
type: String
},
height: {
type: String
}
},
computed: {
getName () {
return `#icon-${this.name}`
},
getClassName () {
return [
'icon-svg',
`icon-svg__${this.name}`,
this.className && /\S/.test(this.className) ? `${this.className}` : ''
]
}
}
}
</script>
<style>
.icon-svg {
width: 1em;
height: 1em;
fill: currentColor;
overflow: hidden;
}
</style>
最后在main.js中引用就行了
import "./icons" // api: http://www.iconfont.cn/
引用方法:
<icon-svg name="zhedie"></icon-svg>
<icon-svg name="shezhi" class="el-icon-setting"></icon-svg>
好了,到这里就完了!!!