记录下vue 项目使用svgicon过程

目的是记录一下使用的过程
1.参考大佬文章:https://juejin.cn/post/6844903517564436493

2.新建svgicon组件,具体代码见开源:https://gitee.com/panjiachen/vue-admin-template?_from=gitee_ 

 1 <template>
 2   <div v-if="isExternal" :style="styleExternalIcon" class="svg-external-icon svg-icon" v-on="$listeners" />
 3   <svg v-else :class="svgClass" aria-hidden="true" v-on="$listeners">
 4     <use :xlink:href="iconName" />
 5   </svg>
 6 </template>
 7 
 8 <script>
 9 import { isExternal } from '@/util/validate'
10 
11 export default {
12   name: 'SvgIcon',
13   props: {
14     iconClass: {
15       type: String,
16       required: true
17     },
18     className: {
19       type: String,
20       default: ''
21     }
22   },
23   computed: {
24     isExternal() {
25       return isExternal(this.iconClass)
26     },
27     iconName() {
28       return `#icon-${this.iconClass}`
29     },
30     svgClass() {
31       if (this.className) {
32         return 'svg-icon ' + this.className
33       } else {
34         return 'svg-icon'
35       }
36     },
37     styleExternalIcon() {
38       return {
39         mask: `url(${this.iconClass}) no-repeat 50% 50%`,
40         '-webkit-mask': `url(${this.iconClass}) no-repeat 50% 50%`
41       }
42     }
43   }
44 }
45 </script>
46 
47 <style scoped>
48 .svg-icon {
49    1em;
50   height: 1em;
51   vertical-align: -0.15em;
52   fill: currentColor;
53   overflow: hidden;
54 }
55 
56 .svg-external-icon {
57   background-color: currentColor;
58   mask-size: cover!important;
59   display: inline-block;
60 }
61 </style>

3.新建icons目录,index.js做图标引入与组件的注册处理,svg目录存放iconfont下载回来的svg文件

1 import Vue from 'vue'
2 import SvgIcon from '@/components/SvgIcon'// svg component
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.main.js引入icons目录:

import '@/icons' // icon
 
 
5.先安装插件   svg-sprite-loader  :  npm install --save svg-sprite-loader
然后再vue.config.js 中   配置svg-sprite-loader

 1 const path = require('path')
 2 
 3 function resolve(dir) {
 4   return path.join(__dirname, dir)
 5 }
 6 
 7 module.exports = {
 8   chainWebpack(config) {
 9     // set svg-sprite-loader
10     config.module
11       .rule('svg')
12       .exclude.add(resolve('src/icons'))
13       .end()
14     config.module
15       .rule('icons')
16       .test(/\.svg$/)
17       .include.add(resolve('src/icons'))
18       .end()
19       .use('svg-sprite-loader')
20       .loader('svg-sprite-loader')
21       .options({
22         symbolId: 'icon-[name]'
23       })
24       .end()
25 
26   }
27 }

 6.在相应页面使用

原文地址:https://www.cnblogs.com/chchchc/p/15736443.html