cnpm install -S svg-sprite-loader
? ? ? ? src/SvgIcon/index.vue
<template>
<svg :class="svgClass" aria-hidden="true" v-on="$listeners">
<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>
? ? ? ? src/assets/icons/index.js
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon/index.vue'// svg component
// register globally
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
import '@/assets/icons/index'
const path = require('path')
function resolve (dir) {
return path.join(__dirname, dir)
}
module.exports = defineConfig({
transpileDependencies: true,
// svg
chainWebpack: config => {
config.module
.rule('svg')
.exclude.add(resolve('src/assets/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/assets/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
}
})
<!-- icon-class的值对应的是目录中svg的名子 -->
<svg-icon icon-class="user"></svg-icon>
?