1.npm导包
java
npm i svg-sprite-loader --save
2.创建目录放入svg文件,创建SvgIcon.js
![](https://i-blog.csdnimg.cn/direct/ff65a61db1ff4ae9a2d692e3e9022378.png)
3.SvgIcon.js
javascript
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
4.vue.config.js文件中配置
javascript
const path = require('path');
module.exports = {
chainWebpack(config) {
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()
}
}
5.在src/compoments/SvgIcon下创建SvgIcon.vue
java
<template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="iconName"/>
</svg>
</template>
<script>
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>
6.main.js
java
import './icons/SvgIcon.js' //vue中使用svg
import SvgIcon from './components/SvgIcon/SvgIcon.vue'//vue中使用svg
Vue.component('svg-icon', SvgIcon)//vue中使用svg
7.使用方法
java
<template>
<div>
<svg-icon class-name="xxxx" icon-class="xxxx"/>
</div>
</template>
<script>
export default {
name: 'test',
}
</script>
<style>
.star-icon {
font-size: 30px;
color: gold;
}
</style>
8.红框里的就是svg-icon效果
![](https://i-blog.csdnimg.cn/direct/ce152a2628fb479e937451c71841f63c.png)