使用vite-plugin-svg-icons插件
yarn add vite-plugin-svg-icons -D
vite.config.ts 中的配置插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
plugins: [
vue(),
vueJsx(),
createSvgIconsPlugin({
// 指定需要缓存的图标文件夹
iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')],
// 指定symbolId格式
symbolId: 'icon-[name]',
}),
],
在 src/main.ts 内引入注册脚本
import 'virtual:svg-icons-register'
如何在组件使用
/src/components/SvgIcon.vue
<template>
<svg aria-hidden="true" width="40px" height="40px">
<use :xlink:href="symbolId" />
</svg>
</template>
<template>
<svg aria-hidden="true" width="40px" height="40px">
<use :xlink:href="symbolId" fill="color"/>
</svg>
</template>
<script lang="ts" setup>
import { computed } from 'vue';
interface IProps {
/** svg 的图标的名称 */
iconName: string,
color: string,
}
const props = defineProps<IProps>();
const symbolId = computed(() => `#icon-${props.iconName}`);
</script>
使用
<base-svg icon-name="loading" />
网友评论