1.npm导包
npm i svg-sprite-loader --save
2.创建目录放入svg文件,创建SvgIcon.js
3.SvgIcon.js
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
4.vue.config.js文件中配置
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
<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
import './icons/SvgIcon.js'
import SvgIcon from './components/SvgIcon/SvgIcon.vue'
Vue.component('svg-icon', SvgIcon)
7.使用方法
<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效果