src\icons\index.js
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon' // svg组件
Vue.component('svg-icon', SvgIcon)
const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('./svg', true, /\.svg$/)
const iconMap = requireAll(req)
components/SvgIcon/index.vue
<!--
* @Description: 文件描述
* @Author: yx
* @Date: 2023-05-09 10:54:09
* @LastEditors: yx
* @LastEditTime: 2023-05-09 17:29:52
-->
<template>
<svg :class="svgClass" aria-hidden="true">
<title v-if="title">{{title}}</title>
<use :xlink:href="iconName"></use>
</svg>
</template>
<script>
export default {
name: 'svg-icon',
props: {
iconClass: {
type: String,
required: true,
},
className: {
type: String
},
title: {
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>
main.js
import './icons'
使用:
其实此时还不能正确的显示出来,还需要经过如下配置,在vue.config.js文件夹下进行配置,添加如下信息:
config.module.rule('svg').exclude.add(resolve('src/icons/svg')).end()
config.module.rule('icons').test(/\.svg$/)
.include.add(resolve('src/icons/svg')).end()
.use('svg-sprite-loader').loader('svg-sprite-loader').options({
symbolId: 'icon-[name]'
}).end()
发现还是不行,只需要安装依赖:
npm i svg-sprite-loader --save
然后就可以使用了