配置好后可以轻松从iconfont导入svg图标或者任意svg图标。
参考:https://blog.csdn.net/weixin_39729729/article/details/137348970
https://blog.csdn.net/CMDN123456/article/details/139854354
官网https://www.iconfont.cn/help/detail?spm=a313x.help_detail.i1.d8d11a391.550b3a81PTK8cM&helptype=code
重点是 symbol 引用,以下是vite配置使用的方式:
-
首先安装 pnpm add vite-plugin-svg-icons -D,然后配置:
// vite.config.ts import { resolve } from "path" import { createSvgIconsPlugin } from "vite-plugin-svg-icons" const pathSrc = resolve(__dirname, "src") export default defineConfig({ ... plugins: [ createSvgIconsPlugin({ // 指定需要缓存的图标文件夹,也就是项目实际存放svg图标的文件夹 iconDirs: [resolve(pathSrc, "assets/icons")], // 指定symbolId格式 symbolId: "icon-[name]", }), ] })
-
项目的main.ts中导入:
// 本地SVG图标 import "virtual:svg-icons-register"
-
参考这个组件 SvgIcon 写法,需要使用iconfont图标时,直接在调用组件时传入 :icon-class=“图标名” 即可,例如:<svg-icon :icon-class=" isFullscreen ? ‘fullscreen-exit’ : ‘fullscreen’ " /> (fullscreen-exit和fullscreen是两个图标)。图标存放地址,例如:src/assets/icons/fullscreen.svg
<!-- SvgIcon.vue -->
<template>
<svg
aria-hidden="true"
class="svg-icon"
:style="'width:' + size + ';height:' + size"
>
<use :xlink:href="symbolId" :fill="color" />
</svg>
</template>
<script setup lang="ts">
const props = defineProps({
prefix: {
type: String,
default: "icon",
},
iconClass: {
type: String,
required: false,
default: "",
},
color: {
type: String,
default: "",
},
size: {
type: String,
default: "1em",
},
});
const symbolId = computed(() => `#${props.prefix}-${props.iconClass}`);
</script>
<style scoped>
.svg-icon {
display: inline-block;
width: 1em;
height: 1em;
overflow: hidden;
vertical-align: -0.15em; /* 因icon大小被设置为和字体大小一致,而span等标签的下边缘会和字体的基线对齐,故需设置一个往下的偏移比例,来纠正视觉上的未对齐效果 */
outline: none;
fill: currentcolor; /* 定义元素的颜色,currentColor是一个变量,这个变量的值就表示当前元素的color值,如果当前元素未设置color值,则从父元素继承 */
}
</style>