如何在Vue项目中优雅的使用svg图标
# 如何在Vue项目中优雅的使用svg图标
# 一、SVGO
# 1. SVGO
是什么
基于Nodejs的SVG文件优化工具
为什么需要SVGO?因为SVG文件,尤其从各种编辑器导出的SVG,通常包含大量的无用信息,例如编辑器源信息,注释,因此元素,默认或者非最优值,以及其他一些不会影响渲染结果的可以移除或转换的内容。
# 2. 安装
svgo github (opens new window)
npm -g install svgo
oryarn global add svgo
# 3. 使用
- 单文件使用:
$ svgo test.svg
1
- 文件夹使用
$ svgo -f ../path/to/folder/with/svg/files
1
or
$ svgo -f ../path/to/folder/with/svg/files -o ../path/to/folder/with/svg/output
1
# 二、 在vue项目中使用svg图标
# 1. 项目中安装svg-sprite-loader
npm install svg-sprite-loader
or yarn add svg-sprite-loader
# 2. 基于vue-cli2.x项目webpack配置
配置build文件夹中的webpack.base.conf.js文件
//注意 url-loader 中要将 icons 文件夹排除, 不让 url-loader 处理该文件夹
exclude: [resolve('src/icons')],
{
test: /\.svg$/,
loader: 'svg-sprite-loader',
include: [resolve('src/icons')],
options: {
symbolId: 'icon-[name]'
}
},
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 3. 基于 vue-cli3.x 和 cli4.x 项目 webpack 配置
配置根目录中的 vue.config.js 文件
chainWebpack: (config) => {
const svgRule = config.module.rule('svg')
// 清空默认svg规则
svgRule.uses.clear()
// 针对svg文件添加svg-sprite-loader规则
svgRule
.test(/\.svg$/)
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 4. 封装SvgIcon组件
在src->components中新建SvgIcon文件,在SvgIcon下创建index.vue
<template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
export default {
name: 'SvgIcon',
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: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
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
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
# 5. 全局注册svg组件
在 src 下新建 icons 文件夹,在 icons下新建 index.js 和 svg文件夹,svg文件夹用于存放 svg 图片,index.js 用于加载所有 svg 文件和全局注册组件
import Vue from 'vue'
import SvgIcon from '../components/SvgIcon/index'//svg组件
//全局注册组件
Vue.component('svg-icon', SvgIcon)
// 定义一个加载目录的函数
const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('./svg', false, /\.svg$/)
// 加载目录下的所有的 svg 文件
requireAll(req)
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
├─components
│ │ HelloWorld.vue
│ │
│ └─SvgIcon
│ index.vue
│
├─icons
│ │ index.js
│ │
│ └─svg
│ alarm.svg
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 6. 在main.js中引入icons文件
// 引入 icons
import './icons'
1
2
2
# 7. 使用方法
//class-name:svg图片的样式类名
<svg-icon icon-class="time" class-name="icon" />
1
2
2
.icon {
width: 50px;
height: 50px;
color: red;
}
1
2
3
4
5
6
2
3
4
5
6
# 8.可能遇到的问题
- 宽高样式不生效:在样式后面加上 !important
- 颜色不生效:打开 svg 文件,删除文件中所有的 fill 属性
上次更新: 11/4/2021, 10:51:59 AM