项目添加svgIcon
呛再首 4/5/2020 Vue技巧
# 项目添加svgIcon
- 安装
npm i svg-sprite-loader -S
1
- vue.config.js 中的 chainWebpack 修改
const path = require('path')
function resolve(dir) {
return path.join(__dirname, './', dir)
}
...
module.exports = {
chainWebpack(config) {
// set svg-sprite-loader
config.module
.rule('svg')
.exclude.add(resolve('src/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
}
}
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
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
src下新建icons文件夹放svg文件
编写svgIcon 组件,components下新建
SvgIcon.vue
<template>
<svg :class="svgClass" aria-hidden="true"
// /* aria-hidden="true"将元素从可访问树上移除 */
v-on="$listeners">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
export default {
name: 'SvgIcon',
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 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
43
44
45
46
47
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
44
45
46
47
- main.js中
import SvgIcon from '@/components/SvgIcon'
const req = require.context('./icons', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
Vue.component('svg-icon',SvgIcon) // 全局注册
1
2
3
4
5
6
7
2
3
4
5
6
7
- 使用
<svg-icon
icon-class="ch"
style="width: 2em; height: 2em;vertical-align:middle"
></svg-icon>
1
2
3
4
2
3
4
svg图标封装组件 (opens new window)、vue-element-admin使用svg图标 (opens new window)