svg-icon 组件配置
- npm i svg-sprite-loader@4.1.3
- 在src下创建icons文件夹,icons文件夹下创建svg文件夹和index.js

- index.js:
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
- svg文件夹:可在iconfont中下载svg文件放入svg文件夹。

- 创建SvgIcon组件:在components文件夹下创建SvgIcon文件夹,下创建index.vue文件

- index.vue :
<template
<svg v-else :class="svgClass" 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>
- 在main.js 导入 icons文件夹下的 index.js :

- 最后vue.config.js: vue.config.js修改了要重启项目。否则不生效。
{
chainWebpack (config) {
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()
}
}
使用:<svg-icon icon-class="文件名"/> 文件名就是在src/icons/svg下的文件名