Skip to content

about

对于iconfont的几种图标介绍,优缺点,参考这个链接:https://developer.aliyun.com/article/975701

我这里把我配置的步骤记录下.

配置步骤

自定义SvgIcon图标组件

有了自定义SvgIcon图标组件,将来我们可以在任意文件中以组件的形式使用iconfont图标.

创建js文件,并注册到main.js中,以下文件中路径和文件名不存在就创建.

vue
<!-- src/components/SvgIcon/SvgIcon.vue -->
<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: '#409eff'  // 默认的图标颜色
    }
});

// 图标在 iconfont 中的名字
const iconClassName = computed(()=>{
    return `#${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>

symbol 模式引入图标

symbol 模式引入图标,这里我介绍三种引入方式。

第一种:

直接在线引入官网提供的在线 js 地址,我们直接以 script 标签的形式引入即可。这种方式最为简单,但是也有不好的一点,需要用户有网络环境,而且得保证 iconfont 网站没有崩掉。

第二种:

直接下载至本地,我们从官网直接将代码下载下来,然后放到我们项目中引用,也是可以的。不过这种方式稍显麻烦,每次更新图标库之后都得重新下载一遍。

第三种:

这也是我比较喜欢的方式,也就是将在线地址中的代码直接复制粘贴到我们项目中来,这种方式最为简单,每次更新图标库之后只需要重新复制一下代码即可。这里我们也将采用这种方式。

具体使用:

在项目 assets 目录下新建 iconfont 目录,在该目录下新建 iconfont.js 文件,然后将 iconfont 在线地址中提供的代码全部复制过来。在线地址就是如下标记的位置.

1832671034071842816.png

1832671034956840960.png

1832671037469229056.png

注册到main.js

全局的main.js文件中,将iconfont和自定义组件进行导入和注册,方便将来在任意组件中直接使用.

javascript
import { createApp } from 'vue'
// import './style.css'
import App from './App.vue'
import router from "./router/index";
import ELementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import $axios from "./utils/axios";
import store from './store'
import SvgIcon from "@/components/SvgIcon/SvgIcon.vue";  // 引入自定义iconfont图标组件
import './assets/iconfont/iconfont.js';  // 引入iconfont图标的js文件内容
const app = createApp(App)
app.use(router)
app.use(store)
app.use(ELementPlus)
app.config.globalProperties.$axios = $axios;
app.component('SvgIcon', SvgIcon)  // 注册自定义iconfont图标的组件,将来在任意组件中直接使用
app.mount('#app')

文件中使用图标

任意文件中直接引用,只需要去iconfont官网,自己的项目中,symbol选项,复制图标的代码.

1832671038165483520.png

然后将复制的代码,替换到iconName的值即可,图标显示出来了.

vue
<el-button type="success" @click="doAddMobile"><el-icon><Plus /></el-icon>&nbsp;新增</el-button>
<el-button type="waning" @click="doAddKeyword">
    <!-- 如果想自定义图标颜色,就给color,不传就用默认的颜色 -->
    <svg-icon iconName="icon-xinzeng" color="#409eff"></svg-icon>
    &nbsp;批量上传</el-button>
<el-button type="success" @click="doAddKeyword"><el-icon><Plus /></el-icon>&nbsp;修改</el-button>
<el-button type="primary"><el-icon><Download /></el-icon>&nbsp;导出</el-button>

效果,红框标记的是iconfont的图标,其它的是element-plus图标.

1832671038773657600.png240721140729220.png)