1、安装一下依赖
npm install vite-plugin-svg-icons -D
2、在vite.config.ts中
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
const { resolve } = require('path');
plugins:[createSvgIconsPlugin({// 配置你存放 svg 图标的目录iconDirs: [resolve(process.cwd(), 'svg文件夹所在的目录')],//例如:src/images/svg// 定义 symbolId 格式symbolId: 'icon-[dir]-[name]',})
]
3、封装一个svg组件
<template><svg :class="svgClass" aria-hidden="true"><use :xlink:href="iconName" :fill="color"></use></svg>
</template><script>
import { computed, defineComponent } from 'vue';
export default defineComponent({props: {iconClass: {type: String,required: true,},className: {type: String,default: '',},color: {type: String,default: '#889aa4',},},setup(props) {return {iconName: computed(() => `#icon-${props.iconClass}`),svgClass: computed(() => {if (props.className) {return `svg-icon ${props.className}`;}return 'svg-icon';}),};},
});
</script><style scope>
.svg-icon {width: 1em;height: 1em;fill: currentColor;vertical-align: middle;
}
</style>
4、继续引入
//在main.ts中
import 'virtual:svg-icons-register';
//在main.ts中全局引入
import svgIcon from '组件地址';
app.component('svgIcon', svgIcon);
记录一下,方便后续查阅