首先去阿里巴巴下载几张svg图片,然后新建iconfont文件夹用来存放svg相关,并新建index.js
index.js代码
// 引入 svg 目录下所有文件
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
然后在components目录下新建svgIcon.vue
<template>
<svg :class="svgClass" aria-hidden="true" v-on="$listeners">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
export default {
name: 'svgIcon',
props: {
name: {
type: String,
default: ''
}
},
computed: {
iconName() {
return `#icon-${this.name}`
},
svgClass() {
if (this.name) {
return 'svg-icon ' + this.name
}
return 'svg-icon'
}
}
}
</script>
<style scoped>
.svg-icon {
width: 1.5em;
height: 1.5em;
vertical-align: middle;
fill: currentColor;
overflow: hidden;
}
</style>
由于我的项目是使用webpack搭建的,要修改一下webpack的配置
注意:如果你使用了url-loader
来解析svg文件的话是不行的,要使用svg-sprite-loader
,不然svg不会显示;命令:npm install svg-sprite-loader -D
安装完成后打开webpack.config.js来修改配置,这里只展示svg相关配置
{
test: /\.svg$/,
include: [path.resolve('./src/assets/iconfont/svg')],
use: {
loader: 'svg-sprite-loader',
options: {
symbolId: 'icon-[name]'
}
}
},
{
test: /\.(png|svg|jpg|gif|woff|ttf|webp|eot|woff2)$/,
exclude: [path.resolve('./src/assets/iconfont/svg')],
use: {
loader: 'url-loader',
options: {
limit: 3 * 1024,
outputPath: 'images', // 将文件打包到哪里
publicPath: 'images/',
}
}
},
在菜单组件引入svgIcon组件
menu.vue代码
components: {
svgIcon(resolve) {
require(["../components/svgIcon"], resolve)
}
},
路由文件里面的icon名称要和你svg里面的文件民对应起来
最后在main.js中引入iconfont文件夹下的index.js
如果项目是使用脚手架创建的,那么就要在vue.config.js
配置
const path = require('path')
module.exports = {
chainWebpack: config => {
config.entry('main').add('babel-polyfill') // main是入口js文件
// 其他配置
config.module
.rule('svg')
.exclude.add(path.resolve(__dirname,"src/icons"))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(path.resolve(__dirname,"src/icons"))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
},
}