vue-cli中使用svgIcon

一、安装依赖包

1
2
3
npm install svg-sprite-loader -D
或者
yarn add svg-sprite-loader -D

二、配置vue.config.js文件

在顶部写入

1
2
3
4
const path = require('path')
function resolve (dir) {
return path.join(__dirname, dir)
}

在chainWebpack中增加下列配置

1
2
3
4
5
6
7
8
9
10
chainWebpack (config) {
config.module.rule('svg')
.exclude.add(resolve('src/icons'))
config.module.rule('icons')
.test(/\.svg$/)
.include.add(resolve('./src/icons')).end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({ symbolId: 'icon-[name]' })
}

三、实现SvgIcon组件

组件结构如下:

1
2
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 {
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 lang="scss">
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>

四、根目录下创建icons/svg目录

用于存放我们所需要用的svg文件

五、新建plugins目录及index.js文件

1
2
3
4
5
6
7
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'

const req = require.context('@/icons/svg', true, /\.svg$/)
req.keys().map(req)

Vue.component('svg-icon', SvgIcon)

其作用是在Vue实例上创建SvgIcon组件,其中require.context的作用是获取一个特定的上下文,遍历文件夹中的指定文件,主要用来实现自动化导入模块

  • 最后在main.js中引入plugins, import '@/plugins'

六、SvgIcon 组件的使用

1
<svg-icon icon-class="icon-name" class="down"></svg-icon>

其中icon-class为svg文件名, class为类名