vue3 中 element-plus 图标的全局注册,便捷使用

element-plus的icon有一个比较大的变化就是所有的图标以组件的格式渲染,这样的话我们在使用的时候就需要用一个注册一个,虽然节约了性能,但是实际应用中会带来很多麻烦。所以我选择牺牲这点性能换去方便

1:安装"@element-plus/icons",注意element-plus的图标库需要单独安装
npm install @element-plus/icons

2:入口文件(main.ts)中引用并注册

import { createApp} from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
// 引入所有图标
import * as Icons from '@element-plus/icons'
const app = createApp(App)
// 循环注册所有图标
for(const name in Icons){
    //name 为icon名称,也是组件名称。使用时:<Edit />,
    //也可以按需增加前缀或者后缀
    // eg: app.component(`eurake-name-${name}`,(Icons as any)[name])
    // 使用时:<eurake-name-Edit />
    // 当然你也可以写一个方法把首字母大写的图标名称改成小写等你想要的任意格式
  app.component(name,(Icons as any)[name])
}
//
app.use(ElementPlus).mount('#app')

3:组件中使用

<template>
  <Edit />
</template>
<script setup>
</script>
<style lang="scss" scoped>
</style>

4:样式
可以设置全局样式,默认宽高为1em * 1em ;颜色等可以用fill

svg{
width:1em;
height:1em;
fill:#ddd;//颜色
}

评论

暂无评论