一、安装:
npm i vite-plugin-svg-icons -D
二、main.js中引入
import 'virtual:svg-icons-register'
三、svg图片路径src/assets/svg/xxx.svg
四、vite.config.js配置
import path from 'path' import { createSvgIconsPlugin } from 'vite-plugin-svg-icons' export default defineConfig({ plugins: [ createSvgIconsPlugin({ // 指定要缓存的文件夹 iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')], // 指定symbolId格式 symbolId: '[name]' }) ] })
五、svg组件封装src/components/SvgIcon.vue
<script setup> import { defineProps, computed } from "vue"; const props = defineProps({ name: { type: String, required: true }, color: { type: String, default: '' }, size: { type:[Number,String], default: 14 } }) const iconName = computed(() => `#${props.name}`) const svgClass = computed(() => { console.log(props.name, "props.name") if (props.name) { return `svg-icon ${props.name}` } return "svg-icon" }) </script> <template> <svg :class="svgClass" :style="{ size + 'px', height: size + 'px' }" > <use :xlink:href="iconName" :fill="color" /> </svg> </template> <style scoped> .svg-icon { fill: currentColor; vertical-align: middle; } </style>
六、全局引入组件
import svgIcon from './components/SvgIcon.vue'
createApp(App).component('svg-icon',svgIcon).use(router).use(ElementPlus).mount('#app')
或者局部引入Home.vue
<script setup>
import svgIcon from '../components/SvgIcon.vue'
</script>
<template>
<SvgIcon name="operationManage" color="red"></SvgIcon>
</template>
参考:
https://blog.csdn.net/weixin_53731501/article/details/125478380