在vue3+vite2中使用svg
1、安装vite-plugin-svg-icons
此处还需要安装下fast-glob相关依赖,不然vite运行npm run dev时会报Cannot find module 'fast-glob’的错误
yarn add fast-glob@3.x -D`
`yarn add vite-plugin-svg-icons@2.x -D`
2、新建组件 svg-icon
在src/components文件夹中新建svg-icon.vue文件
<template>
<svg aria-hidden="true" class="svg-icon">
<use :xlink:href="symbolId" rel="external nofollow" :fill="color" />
</svg>
</template>
<script setup lang="ts">
import {
computed } from 'vue';
const props = defineProps({
prefix: {
type: String,default: 'icon',},
iconClass: {
type: String,required: true,},
color: {
type: String,default: ''}
})
const symbolId = computed(() => `#${
props.prefix}-${
props.iconClass}`);
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
overflow: hidden;
fill: currentColor;
}
</style>
3、vite.config.ts 中的配置插件
import {
resolve } from 'path'
import {
createSvgIconsPlugin } from 'vite-plugin-svg-icons'
export default defineConfig({
plugins: [
createSvgIconsPlugin({
// 指定需要缓存的图标文件夹
iconDirs: [resolve(process.cwd(), 'src/assets/imgs/svg')],
// 指定symbolId格式
symbolId: 'icon-[dir]-[name]',
})
]
})
4、在main.ts全局注册组件
import {
createApp } from 'vue'
import App from './App.vue'
import router from '@/router'
import {
store, key } from '@/store'
const app = createApp(App)
import 'virtual:svg-icons-register' // 引入注册脚本
import SvgIcon from '@/components/svgIcon/index.vue' // 引入组件
app.component('svg-icon', SvgIcon)
app.use(router).use(store, key).mount('#app')
5、在页面中使用
<template>
<svg-icon icon-class="category"></svg-icon>
<svg-icon icon-class="accountant" style="width: 10em; height: 10em;"></svg-icon>
</template>