前提
Element UI
和 Element Plus
对 Icon 图标
的使用方式改变较大,在此记录。
- Element UI Icon 图标:使用CSS 类名方式;
- Element Plus Icon 图标:使用Vue 组件方式;
安装
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 的项目搭建》
方式一
中引入:
-
代码第
6
行,引入所有图标; -
代码第
10-13
行,全局注册图标;
import { createApp } from 'vue'
import './'
import App from './'
import ElementPlus from 'element-plus'
import 'element-plus/dist/'
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')
有两种使用方式:
- 结合
el-icon
使用,提供了额外的属性,如:is-loading
等; - 直接使用
SVG
图标,当做一般的svg
使用;
<!-- 结合 el-icon 使用 -->
<el-icon class="is-loading">
<Operation />
</el-icon>
<!-- 直接使用 SVG 图标 -->
<Operation />
效果:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-muWQyl9P-1675921794620)(./images/)]
方式二
步骤一:新建文件 src/utils/
// 全部小写,且加上 el-icon-,如:el-icon-xxx。这样更清晰
export const toIconLine = (value: string) => {
return 'el-icon-' + value.replace(/(A-Z)/g, '-$1').toLocaleLowerCase()
}
步骤二:中引入
- 代码第
6-7
行,引入所有图标和转行方法; - 代码第
11-16
行,全局注册图标组件,且使用方式有改变;
import { createApp } from 'vue'
import './'
import App from './'
import ElementPlus from 'element-plus'
import 'element-plus/dist/'
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')
步骤三: 中设置
svg
高宽
<style>
svg {
width: 1em;
height: 1em;
}
</style>
同样,有两种使用方式:
- 结合
el-icon
使用,提供了额外的属性,如:is-loading
等; - 直接使用
SVG
图标,当做一般的svg
使用;
<!-- 结合 el-icon 使用 -->
<el-icon class="is-loading">
<el-icon-operation />
</el-icon>
<!-- 直接使用 SVG 图标 -->
<el-icon-operation />
效果:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IK4lZ8Df-1675921794621)(./images/)]
总结
方式一 和 二 的区别:
前者直接使用大驼峰方式使用图标,如 <Operation />
。后者使用小驼峰加横杠,如 <el-icon-operation />
。更清晰,避免组件重名。