為什么要全局注冊颗祝?
element改版了,所有圖標(biāo)已經(jīng)變成了組件文留,以svg的形式來展示
1.下載element-plus/icons圖標(biāo)包
npm install @elements/icons
2.在main.ts中引入
import *as Icons from '@element-plus/icons'
3.全局注冊圖標(biāo)
//全局注冊圖標(biāo)泞边,犧牲一點性能
//el-icon-xxx
for(let i in Icons){
}
4.在src目錄下創(chuàng)建一個utils目錄(存放工具函數(shù))勺卢,在utils目錄下創(chuàng)建一個index.ts文件,寫入方法,把駝峰轉(zhuǎn)換成橫杠連接
//把駝峰轉(zhuǎn)換成橫杠連接
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)
//全局注冊圖標(biāo)尽狠,犧牲一點性能
//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.若是沒有什么特殊要求衔憨,在這里,我們將圖標(biāo)大小統(tǒng)一設(shè)置成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>