安装依赖
npm install svg-sprite-loader --save-dev
配置信息
配置build文件夹中的webpack.base.conf.js,主要在两个地方添加代码。
exclude: [resolve('src/icons')],
{
test: /\.svg$/,
loader: 'svg-sprite-loader',
include: [resolve('src/icons')],
options: {
symbolId: 'icon-[name]'
}
},

微信截图_20200401083042.png
创建文件
1.在src/components下新建文件夹及文件SvgIcon/index.vue

微信截图_20200401083443.png
代码
<template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="iconName"></use>
</svg>
</template>
<script>
export default {
name: 'svg-icon',
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String
}
},
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: 1.2em;
height: 1.2em;
vertical-align: -0.18em;
fill: currentColor;
overflow: hidden;
}
</style>
2.在src下新建icons文件夹,及icons文件夹下svg文件夹、index.js文件

微信截图_20200401083646.png
svg 文件夹用来存放图标
index.js 文件代码
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg组件
// register globally
Vue.component('svg-icon', SvgIcon)
const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('./svg', false, /\.svg$/)
requireAll(req)
3.在main.js中引入svg
import '@/icons' // icon
使用
- 可以去阿里巴巴矢量图标库下载svg格式图标
- 将svg格式图标存放在
src/icons/svg文件架下 - 在页面中使用
<svg-icon icon-class="svg-name"></svg-icon>
svg-name为你所下载svg格式图标的名称,如你的图片名为text.svg,只需将svg-name改为text即可
