下载插件vite-plugin-svg-icons
yarn add vite-plugin-svg-icons -D
配置vite.config.ts
export default defineConfig({
plugins: [vue(),
createSvgIconsPlugin({
// 指定需要缓存的图标文件夹,即图标放置位置
iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')],
// 指定symbolId格式,相当于唯一标识,也可以写成icon-[name]等等,[name]这样写代表是name变量,这个必须以含有[name]的字符串当作唯一标识不然会报错
symbolId: '[name]',
// inject?: 'body-last' | 'body-first'
// customDomId: '__svg__icons__dom__',
})
]
})
创建svg组件
<template>
<svg aria-hidden="true" class="svg-icon" :width="props.width" :height="props.height">
<use :xlink:href="symbolId" :fill="props.color" />
</svg>
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{
width: string,
height: string,
color: string,
name: string
}>()
const symbolId = computed(() => `#${props.name}`)
</script>
<style scoped></style>
全局注册svg组件
import 'virtual:svg-icons-register'
import SvgIcon from '@/components/SvgIcon.vue'
const app = createApp(App)
app.component('svg-icon', SvgIcon)
使用
<svg-icon name="title" width="104px" height="24px" />