1.vue.config.js
loader处理
module.exports = defineConfig({
chainWebpack: config => {
//排除icons目录中svg文件处理
config.module.rule('svg')
.exclude.add(resolve('src/icons'))
.end()
//设置svg-sprite-loader处理icons目录中的svg
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()
}
2.新建index.js
// 自动导入的方法
export function importAllSvg() {
const importAll = (requireContext) =>
requireContext.keys().forEach(requireContext)
try {
// 导入src/icons/svg下的所有以.svg结尾的文件
importAll(require.context('@/icons', false, /\.svg$/))
} catch (error) {
console.log(error)
}
}
3.写一个svg的公共组件
<template>
<svg class="svg-icon" aria-hidden="true" v-bind="$attrs" :class="className">
<use :xlink:href="iconName" />
</svg>
</template>
<script setup>
import { toRefs, computed, defineProps } from "vue";
const props = defineProps({
icon: {
type: String,
required: true,
},
svgClass: {
type: String,
default: "",
},
});
const iconName = computed(() => `#icon-${props.icon}`);
const className = computed(() => {
if (props.svgClass === undefined) {
return "";
}
return props.svgClass;
});
</script>
<style lang="less" scoped>
.svg-icon {
width: 1em;
height: 1em;
overflow: hidden;
vertical-align: -0.15em;
fill: currentColor;
}
</style>
4.将index.js引入main,js
import {importAllSvg} from "@/index.js"
importAllSvg()
5.组件中使用
// jince是在icon中定义的svg名字
<template>
<div class="home">
<svgIcon icon="jince"></svgIcon>
</div>
</template>
<script setup>
import svgIcon from "@/components/svgIcon/svgIcon.vue";
</script>
<style scoped lang="less">
</style>