准备工作:
VUE => ^2.5.2
WEBPACK => ^3.6.0
1. 第一步 webpack.base.conf.js
配置对应的loader
1 { 2 test: /.(png|jpe?g|gif|svg)(?.*)?$/, 3 loader: 'url-loader', 4 exclude: [resolve('src/icons')], 5 options: { 6 limit: 10000, 7 name: utils.assetsPath('img/[name].[hash:7].[ext]') 8 } 9 }, 10 { 11 test: /.svg$/, 12 loader: "svg-sprite-loader", 13 include: [resolve('src/icons')], 14 options: { 15 symbolId: "icon-[name]" 16 } 17 }
2.第二步 写SvgIcon组件
业务组件下svg文件夹下
1 <template> 2 <svg :class="svgClass" aria-hidden="true" v-on="$listeners"> 3 <use :xlink:href="iconName" /> 4 </svg> 5 </template> 6 7 <script> 8 export default { 9 name: "SvgIcon", 10 props: { 11 iconClass: { 12 type: String, 13 required: true 14 }, 15 className: { 16 type: String, 17 default: "" 18 } 19 }, 20 computed: { 21 iconName() { 22 return `#icon-${this.iconClass}`; 23 }, 24 svgClass() { 25 if (this.className) { 26 return "svg-icon " + this.className; 27 } else { 28 return "svg-icon"; 29 } 30 } 31 } 32 }; 33 </script> 34 35 <style lang="scss" scoped> 36 .svg-icon { 37 1em; 38 height: 1em; 39 vertical-align: -0.15em; 40 fill: currentColor; 41 overflow: hidden; 42 } 43 44 </style>
3.第三步 把组件挂载到全局
icons 文件夹下的index,js 文件
1 import Vue from 'vue' 2 import SvgIcon from '@/business-components/svg/SvgIcon'// svg组件 3 4 // register globally 5 Vue.component('svg-icon', SvgIcon) 6 7 const req = require.context('./svg', false, /.svg$/) 8 const requireAll = requireContext => requireContext.keys().map(requireContext) 9 requireAll(req)
4.第四步 mian.js引入
import './icons';