安装依赖:
npm install svg-sprite-loader --save-dev
创建svg组件:(src/components/scgIcon/index.vue)
<template>
<svg :class="svgClass" :aria-hidden="true">
<use :xlink:href="iconName" :fill="color" />
</svg>
</template>
<script>
export default {
name: "svg-icon",
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";
}
},
color: {
type: String,
default: "#000",
},
},
};
</script>
<style scoped lang="scss">
.svg-icon {
width: 100%;
height: 100%;
fill: currentColor;
overflow: hidden;
font-size: 30px;
}
</style>
创建svg图标库:(src/icons/svg/home.svg) - 我放在了根目录
引入处理:(src/icons/index.js)
const requireAll = requireContext => requireContext.keys().map(requireContext);
const req = require.context('./svg', false, /\.svg$/);
requireAll(req);
config文件配置:(vue.config.js) - 与根目录(src)同级
const path = require('path');
function resolve(dir) {
return path.join(__dirname, '.', dir)
}
module.exports = {
chainWebpack: config => {
config.module.rules.delete("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()
},
}
main.js全局引入并注册:
import { createApp } from 'vue';
import App from './App.vue';
import SvgIcon from '@/components/svgIcon/index';
import './icons';
const app = createApp(App);
app.component('svg-icon', SvgIcon);
app.mount('#app');
使用svg:
<template>
<div>
<svg-icon icon-class="home"></svg-icon>
</div>
</template>
<script>
export default {
};
</script>
<style scoped lang='scss'>
</style>
修改了vue.config.js文件,记得重启项目
附上我的项目目录: