1、安装svg-sprite-loader
npm install svg-sprite-loader --save-dev
2、在/src/components文件夹下创建SvgIcon.vue
<template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
/**
* 使用栗子
* <svg-icon icon-class="set"></svg-icon>
*/
export default {
name: 'SvgIcon',
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String,
default: ''
}
},
computed: {
iconName () {
return `#icon-${this.iconClass}`
},
svgClass () {
if (this.className) {
return 'svg-icon ' + this.className
} else {
return 'svg-icon'
}
}
}
}
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
3、在src文件夹下新建icons文件夹,icons文件夹下新建svg文件夹,把所有的svg放进这个文件夹里

import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon' // svg组件
// 注册全局组件
Vue.component('svg-icon', SvgIcon)
const requireAll = reqireContext => reqireContext.keys().map(reqireContext)
const req = require.context('./svg', false, /\.svg$/)
requireAll(req)
5、webpack.base.conf.js配置
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
exclude: [resolve('src/icons')],
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
}
{
test: /\.svg$/,
loader: 'svg-sprite-loader',
include: [resolve('src/icons')],
options: {
symbolId: 'icon-[name]'
}
}
6、使用
<svg-icon icon-class="logo"></svg-icon>