- 在./src/components路径下添加通用组件
<template>
<svg :class="svgClass" aria-hidden="true">
<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>
- 在./src/icons/svg/文件夹下添加svg文件
- 修改./src/icons/index.js文件
import SvgIcon from '@/components/tools/SvgIcon' // svg组件
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
export default {
install: (app) => {
app.component("SvgIcon", SvgIcon)
}
}
4.在main.js中将文件引入
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import installElementPlus from './plugins/element'
import SvgIcon from './icons'
console.log('Process',process.env);
const app = createApp(App)
installElementPlus(app)
// 引入SvgIcon
app.use(SvgIcon)
app.use(store).use(router).mount('#app')
- 运用方式
<svg-icon icon-class="password" />
问题解决
svg-icon不显示,后台也报错
- 安装 svg-sprite-loader
npm install svg-sprite-loader --save-dev
需要在vue.config.js中配置
2. 配置vue.config.js文件
在chainWebpack中添加如下代码
chainWebpack: (config) => {
// 添加svg文件
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()
// 编译某些npm包里的es6代码
config.module
.rule('vxe')
.test(/\.js$/)
.include
.add(resolve('node_modules/vxe-table'))
.add(resolve('node_modules/vxe-table-plugin-antd'))
.end()
.use()
.loader('babel-loader')
.end()
}
结束