常用方案
vue3
参考教程:https://juejin.cn/post/7110099190247587854
封装一个/comconents/IconfontIcons.vue
的通过组件入口:
<!--
* @Author: CPS
* @email: 373704015@qq.com
* @Date: 2022-11-06 14:04:15.473252
* @Last Modified by: CPS
* @Last Modified time: 2022-11-06 14:04:15.473252
* @Filename IconFont.vue
* @Description: 这是一个iconfont的通用vue3组件,挂载到全局后,只需要输入对应的iconname即可生成icon
-->
<template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="iconClassName" :fill="color" />
</svg>
</template>
<script setup lang="ts">
import { computed } from "vue";
import "@/assets/icons/iconfont.js";
// 入参
const props = withDefaults(defineProps<{
iconName: string;
className?: string;
color?: string;
iconPrefix?: string;
}>(), {
className: "",
color: "#409eff",
iconPrefix: "icon-yys-",
});
// 图标在 iconfont 中的名字
const iconClassName = computed(() => {
// return `#${props.iconName}`;
return `#${props.iconPrefix}${props.iconName}`;
});
// 给图标添加上其他自定义类名,进行自定义样式
const svgClass = computed(() => {
if (props.className) {
return `svg-icon ${props.className}`;
}
return "svg-icon";
});
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
position: relative;
fill: currentColor;
vertical-align: -2px;
}
</style>
封装完成后,还要将iconfont的资源进行全局的注册main.ts
:
// main.ts
import IconFont from './components/Icons/Iconfont.vue'
const app = createApp(App)
app.component('IconFont', IconFont);
app.mount('#app')
为了确保每次更新方便,这里采用将在线文件拷贝到本地的/iconfont.js
文件中,这样不用每次都重复下载打包文件后解压,更新等操作,只要每次重新拷贝一份在线的js到本地的js即可,且本地只有一个iconfony.js
文件,易于管理。
组件使用:
<template>
<svg-icon iconName="icon-gongzuoleixing"></svg-icon>
<svg-icon iconName="icon-yulan" className="yulan"></svg-icon>
</template>
转换为vue组件
vue官方推荐的方案
<template>
<svg
xmlns="http://www.w3.org/2000/svg"
:width="width"
:height="height"
viewBox="0 0 18 18"
:aria-labelledby="iconName"
role="presentation"
>
<title :id="iconName" lang="en">{{ iconName }} icon</title>
<g :fill="iconColor">
<slot />
</g>
</svg>
</template>
iconfont
vue
首先将需要的图片添加到项目
在
我的项目
页面选择Symbol
格式,将图片下载至本地引入
js
和css
文件import "@/assets/icon/iconfont/iconfont.js";
import "@/assets/icon/iconfont/iconfont.css";
React
本地引用:
- 先从iconfont下载图片文件到本地,(Font class)格式的js文件