为什么要全局注册?
element改版了,所有图标已经变成了组件,以svg的形式来展示
1.下载element-plus/icons图标包
npm install @elements/icons
2.在main.ts中引入
import *as Icons from '@element-plus/icons'
3.全局注册图标
//全局注册图标,牺牲一点性能
//el-icon-xxx
for(let i in Icons){
}
4.在src目录下创建一个utils目录(存放工具函数),在utils目录下创建一个index.ts文件,写入方法,把驼峰转换成横杠连接
//把驼峰转换成横杠连接
export const toLine = (value:string)=>{
return value.replace(/(A-Z)g/,'-$1').toLocaleLowerCase()
}
5.注册全局组件
//注册全局组件
app.component(`el-icon-${toLine(i)}`,(Icons as any)[i])
main.ts文件更新为如下
import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import *as Icons from '@element-plus/icons'
import { toLine } from './utils'
const app =createApp(App)
//全局注册图标,牺牲一点性能
//el-icon-xxx
for(let i in Icons){
//注册全局组件
app.component(`el-icon-${toLine(i)}`,(Icons as any)[i])
}
app.use(router).use(ElementPlus)
app.mount('#app')
6.若是没有什么特殊要求,在这里,我们将图标大小统一设置成1em
在App.vue中,style下
svg{
width: 1em;
height: 1em;
}
APP.vue
<template>
<router-view></router-view>
</template>
<style>
*{
margin: 0;
padding: 0;
}
svg{
width: 1em;
height: 1em;
}
</style>