the first method
- Create a folder icons in src, and then create a svg and a index.js
- svg folder put all the svg
Creating a component SvgIcon code is as follows
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" 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: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>Index.js registered in the global assembly of icons
1
2
3
4
5
6
7<! - first introducing component ->
Import from Vue 'VUE'
Import from SvgIcon '@ / Components / SvgIcon' // SVG component
<-! Sign Components ->
Vue.component('svg-icon',SvgIcon)Use code
1
2<-! svg name is the name to be used ->
<icon icon-SVG-class = "name"> </ SVG-icon>Further use, because it is generated by js svg code disadvantages not intuitive
You can not be loaded on demand
Custom poor
Add unfriendlySo we packed to achieve more by using svg svg-sprite-loader
-
Big Box
vue method used svg
First, install the svg-sprite-loader
1
npm install svg-sprite-loader --save
在vue的build > webpack.base.conf.js中添加svg的模块
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17{
test: /.svg$/,
loader: 'svg-sprite-loader',
include: [resolve('src/icons')],
options: {
symbolId: 'icon-[name]'
}
},
{
test: /.(png|jpe?g|gif|svg)(?.*)?$/,
loader: 'url-loader',
exclude: [resolve('src/icons')], // 这个方法是不包含不打包
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
自动导入 在index.js中添加如下代码
1
2
3const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('./svg', false, /.svg$/)
requireAll(req)最后使用
1
2
3<!--icon-class是所使用的svg名-->
<!--class-name是图标的类名控制-->
<svg-icon icon-class='language' class-name="card-panel-icon" />
10 .重点是要引入
1 |
import '@/icons' |
第二种方法
- 与svg同级创建一个svg文件夹,放入需要的svg
- 使用vue-svgicon
- 通过文档实现svg的使用
- 简单用法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15npm install vue-svgicon --save-dev
<!--配置-->
"svg": "vsvg -s ./static/svg/src -t ./src/icons"
<!--main.js中-->
import * as svgicon from 'vue-svgicon'
Vue.use(svgicon, {
tagName: 'svgicon'
})
<!--home.vue中使用-->
<svgicon name="vue"></svgicon>
<! - execution ->
npm RUN SVG