Vite2+Vue3.2+整合svg
安装vite-plugin-svg-icons插件
yarn add vite-plugin-svg-icons -D
vite.config.ts文件配置
iconDirs设置svg文件位置;
symbolId设置svg名字
export default defineConfig({
plugins: [
createSvgIconsPlugin({
iconDirs: [pathResolve('src/svg/icon')],
symbolId: 'icon-[dir]-[name]',
inject: 'body-last',//body-last|body-first默认body-last
customDomId: '__svg__icons__dom__', //默认__svg__icons__dom__
}),
],
}
main.ts中添加配置
import 'virtual:svg-icons-register'
创建svgIcon.vue文件
<template>
<svg aria-hidden="true">
<use :href="symbolId" :fill="color" />
</svg>
</template>
<script setup lang="ts">
import { computed } from "vue";
interface SvgInfo {
prefix?: string;
name: string;
color?: string;
}
const props = withDefaults(defineProps<SvgInfo>(), {
prefix: "icon",
color: "#333",
});
const symbolId = computed(() => `#${props.prefix}-${props.name}`);
console.log("symbolId:" + symbolId);
const color = computed(() => props.color);
</script>
应用svgIcon.vue组件
<template>
<svgIcon
name="gitee"
@click.native="goto"
style="width: 1.5em; height: 1.5em; font-size: 18px; cursor: pointer"
color="hotpink"
></svgIcon>
</template>
<script setup>
import svgIcon from "@/views/common/svgIcon.vue";
import Icon from "@ant-design/icons-vue";
const url = "https://github.com/AlexhahahaDrag/alex_blog.git";
const goto = () => {
window.open(url);
};
</script
至此就可以完美在项目中使用svg了。
项目地址