目录
- 一、需求描述
- 二、操作步骤
- 1.在iconfont中选择项目需要使用的图标
- 2.在项目中创建iconfont.js
- 3.创建svgIcon组件
 
一、需求描述
- 将iconfont图标库选择的图标以SVG的形式引入项目
- 并通过组件化的形式在项目中引用
- 可控制图标的大小和颜色
二、操作步骤
1.在iconfont中选择项目需要使用的图标

 复制图片中的代码(全部复制)
 
2.在项目中创建iconfont.js
在项目中创建iconfont.js,并将复制的代码粘贴
 
3.创建svgIcon组件
<template><svg :class="svgClass" aria-hidden="true"><use :xlink:href="iconClassName" :fill="color" /></svg>
</template><script setup>
import { computed } from 'vue'
const props = defineProps({iconName: {type: String,required: true},className: {type: String,default: ''},color: {type: String,default: '#333333'},size: {type: String,default: '16px'}
})
// 图标在 iconfont 中的名字
const iconClassName = computed(() => {return `#${props.iconName}`
})
// 给图标添加上类名
const svgClass = computed(() => {if (props.className) {return `svg-icon ${props.className}`}return 'svg-icon'
});
</script><style scoped lang="less">
.svg-icon {/* v-bind 是 Vue3 才支持的功能,可以将 CSS 的值与 js 的值绑定 */width: v-bind('props.size');height: v-bind('props.size');position: relative;fill: currentColor;vertical-align: -2px;
}
</style>-  <template>部分:- <svg :class="svgClass" aria-hidden="true">:定义了一个- <svg>元素,通过- :class动态绑定了类名,根据- svgClass变量的值添加类名。
- <use :xlink:href="iconClassName" :fill="color" />:使用- <use>元素来嵌套引用SVG图标,- xlink:href属性使用了动态绑定,根据- iconClassName变量的值设置图标的引用路径,而- fill属性则根据- color变量的值设置图标的颜色。
 
-  <script setup>部分:- import { computed } from 'vue':引入Vue 3中的- computed函数,用于创建响应式计算属性。
- const props = defineProps({...}):使用- defineProps定义了组件的 props,包括- iconName(图标名称)、- className(类名)、- color(颜色)和- size(大小)等。
- const iconClassName = computed(() => {...}):通过- computed创建一个计算属性- iconClassName,该属性返回一个拼接好的图标类名,用于在- xlink:href中引用对应的SVG图标。
- const svgClass = computed(() => {...}):创建计算属性- svgClass,根据条件动态设置图标的类名,包括了用户传递的- className和默认的- svg-icon类名。
 
-  <style scoped lang="less">部分:- .svg-icon:定义了SVG图标的基本样式,包括宽度、高度、相对定位、填充颜色等。- v-bind('props.size')使用了Vue 3的新特性,将- props.size动态绑定到CSS中,实现图标大小的动态设置。
- vertical-align: -2px;:用于微调图标的垂直对齐,使得图标在垂直方向上更加居中。
 
这个组件允许用户通过传递不同的 iconName、className、color 和 size 属性来渲染不同的SVG图标,并且具有一些默认值。同时,通过使用Vue 3的新特性,使得组件更加灵活和易于使用。