element plus 使用 icon 图标(两种方式)

前提

Element UIElement PlusIcon 图标 的使用方式改变较大,在此记录。

安装

npm

npm install @element-plus/icons-vue

yarn

yarn add @element-plus/icons-vue

使用

必须先安装 element-plus,可使用命令:

npm 方式npm install element-plus --save

yarn 方式yarn add element-plus

如果对整个 vue3项目的搭建有疑问可查看《基于 Vite + Vue3 + TS + sass + router + element-plus 的项目搭建》

方式一

main.ts中引入:

  • 代码第 6 行,引入所有图标;

  • 代码第 10-13行,全局注册图标;

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

const app = createApp(App)

// 全局注册
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.use(ElementPlus)
.mount('#app')

有两种使用方式:

  1. 结合 el-icon 使用,提供了额外的属性,如:is-loading等;
  2. 直接使用 SVG 图标,当做一般的 svg 使用;
<!-- 结合 el-icon 使用 -->
<el-icon class="is-loading">
    <Operation />
</el-icon>
<!-- 直接使用 SVG 图标 -->
<Operation />

效果:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-muWQyl9P-1675921794620)(./images/2-1.png)]

方式二

步骤一:新建文件 src/utils/elements.ts

// 全部小写,且加上 el-icon-,如:el-icon-xxx。这样更清晰
export const toIconLine = (value: string) => {
    return 'el-icon-' + value.replace(/(A-Z)/g, '-$1').toLocaleLowerCase()
}

步骤二:main.ts中引入

  • 代码第6-7行,引入所有图标和转行方法;
  • 代码第11-16行,全局注册图标组件,且使用方式有改变
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { toIconLine } from './utils/elements'

const app = createApp(App)

// 全局注册图标 会牺牲一点性能 el-icon-xxx
for(let i in ElementPlusIconsVue) {
    let name = toIconLine(i);
    console.log(name);
    app.component(name, (ElementPlusIconsVue as any)[i])
}

app.use(ElementPlus)
.mount('#app')

步骤三:App.vue 中设置 svg 高宽

<style>
svg {
  width: 1em;
  height: 1em;
}
</style>

同样,有两种使用方式:

  1. 结合 el-icon 使用,提供了额外的属性,如:is-loading等;
  2. 直接使用 SVG 图标,当做一般的 svg 使用;
<!-- 结合 el-icon 使用 -->
<el-icon class="is-loading">
    <el-icon-operation />
</el-icon>
<!-- 直接使用 SVG 图标 -->
<el-icon-operation />

效果:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IK4lZ8Df-1675921794621)(./images/2-1.png)]

总结

方式一 和 二 的区别:

前者直接使用大驼峰方式使用图标,如 <Operation />。后者使用小驼峰加横杠,如 <el-icon-operation />。更清晰,避免组件重名。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值