Vue中使用svg矢量图

本文主要介绍Vue中如何使用svg矢量图。

1安装svg-sprite-loader

1
2

npm i -S svg-sprite-loader

2更改build/webpack.base.conf.js配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

{
test: /\.svg$/,
loader: 'svg-sprite-loader',
include: [path.resolve(__dirname, '../src/images/icons')],
options: {
//symbolId: 'icon-[name]' //这个没有生效,生效的是默认的name
}
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url',
exclude: [resolve('src/icons')],
query: {
limit: 10000,
name: utils.assetsPath('img/[name].[ext]')
}
}

3下载svg文件并放入src/icons/svg/目录下

推荐阿里图标库 https://www.iconfont.cn/

4封装组件components/common/SvgIcon.vue

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
43

<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.5em;
height: 1.5em;
vertical-align: middle;
fill: currentColor;
overflow: hidden;
}
</style>

5新建src/icons/index.js文件

1
2
3
4
5
6
7
8

import Vue from 'vue'
import SvgIcon from '../../components/common/SvgIcon'
//全局注册
Vue.component('svg-icon', SvgIcon)
const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('./svg', false, /\.svg$/)
requireAll(req)

6main.js中引入

1
2

import './icons'

7使用

1
2

<svg-icon icon-class="search"></svg-icon>
扫一扫,请老师喝水