目录结构
vue.config.js
const path = require('path')
function resolve (dir) {
return path.join(__dirname, dir)
}
module.exports = {
chainWebpack (config) {
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]' })
.end()
}
}
icon/index.js
import Vue from 'vue'
import SvgIcon from '../components/SvgIcon.vue'
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
req.keys().map(req)
SvgIcon.vue
<template>
<svg :class="svgCls" v-on="$listeners">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
export default {
name: 'SvgIcon',
props: {
iconClass: {
type: String,
require: true
},
className: {
type: String,
default: ''
}
},
computed: {
iconName () {
return `#icon-${this.iconClass}`
},
svgCls () {
if (this.className) {
return 'svg-icon ' + this.className
} else {
return 'svg-icon'
}
}
}
}
</script>
<style lang="scss" scoped>
.svg-icon{
width: 1em;
height: 1em;
fill: currentColor;
overflow: hidden;
}
</style>
app.vue
<template>
<div id="app">
<svg-icon className="cls" icon-class="qq"></svg-icon>
</div>
</template>
<script>
</script>
<style lang="scss">
.cls{
color: #0000ff;
}
}
</style>