vue通过vite-plugin-svg-icons插件使用SVG图片
一、安装
npm install vite-plugin-svg-icons -D
or
yarn add vite-plugin-svg-icons -D
二、配置vite.config.js文件
import {createSvgIconsPlugin} from 'vite-plugin-svg-icons'
export default defineConfig({
...
plugins:[createSvgIconsPlugin({
//指定需要缓存的图标文件夹
iconDirs: [path.resolve(process.cwd(),'src/assets/icons/svg')],
// 指定symbolId格式
symbolId: 'icon-[name]'
})],
...
})
(对应svg图片存放位置)
三、在main.js引入
import 'virtual:svg-icons-register'
四、封装svg组件(我的路径:src/components/SvgIcon/index.vue)
<template>
<svg aria-hidden="true" class="svg-icon">
<use :xlink:href="symbolId" />
</svg>
</template>
<script setup>
import { computed } from "vue";
const props = defineProps({
prefix: {
type: String,
default: "icon",
},
name: {
type: String,
required: true,
},
});
const symbolId = computed(() => `#${props.prefix}-${props.name}`);
</script>
<style scope>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
五、页面使用
1、按需引用
<template>
<SvgIcon name="user"></SvgIcon>
</template>
<script setup>
import SvgIcon from "@/components/SvgIcon/index.vue";
</script>
2、全局引用
import SvgIcon from './components/SvgIcon/index.vue'
createApp(App).component("SvgIcon",SvgIcon)