先看使用
在vue组件中的template里
| 1
 | <svg-icon :icon-class="icon-name"></svg-icon>
 | 
SvgIcon.vue
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 
 | <template><svg :class="svgClass" 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>
 
 
 | 
加载svg文件,注册成自定义组件
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | import Vue from 'vue';import SvgIcon from './svgIcon.vue';
 
 const req = require.context('./', false, /\.svg$/);
 req.keys().map(item => req(item));
 
 
 Vue.component('svg-icon', SvgIcon);
 
 
 | 
webpack配置(svg-sprite-loader)
npm install svg-sprite-loader
vue.config.js里面修改配置
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 
 | chainWebpack: config => {
 
 
 config.module.rule('svg').exclude.add(resolve('src/resources/svg'));
 
 
 config.module
 .rule('icons')
 .test(/\.svg$/)
 .include.add(resolve('src/resources/svg'))
 .end()
 .use('svg-sprite-loader')
 .loader('svg-sprite-loader')
 .options({ symbolId: 'icon-[name]' })
 .end();
 }
 
 | 
main.js 中引入
| 1
 | import './resources/svg/index.js'; 
 |