1、安装svg-sprite-loader。
npm install svg-sprite-loader --save-dev
2、/src/components 创建 SvgIcon.vue
<template>
<svg :class="svgClass" aria-hidden="true" v-on="$listeners">
<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目录
- index.js
- svg 目录 存放svg资源
index.js 内容
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', true, /\.svg$/) // 目录递归查找svg
requireAll(req)
4、src/svg/icons 放svg资源
5、vue-config.js配置(一定要放vue.config.js)
const path = require('path')
function resolve (dir) {
return path.join(__dirname, './', dir)
}
module.exports = {
chainWebpack: config => {
// svg loader
config.module
.rule('svg')
.exclude
.add(resolve('src/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include
.add(resolve('src/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
}
}
6、使用
<svg-icon icon-class="eye"></svg-icon>
备注: 修改svg颜色可使用color:red;或者fill:red;