element-plus的el-icon和@element-plusicons vue3 组件封装与使用

使用 element-plus 时发现了一个问题:icon 需要单独安装和引入,让我很是难受,官网是这么说的(大概意思如下):

$ yarn add @element-plus/icons 
# 或者 
$ npm install @element-plus/icons

import { defineComponent } from 'vue' 
import { Edit, Share, Delete, Search } from '@element-plus/icons' 
export default defineComponent({ 
    components: { Edit, Share, Delete, Search } 
})

<template> 
    <div style="font-size: 20px;"> 
    <!-- Since svg icons do not carry any attributes by default --> 
    <!-- You need to provide attributes directly --> 
        <el-icon size="1em"><edit /></el-icon>
        <el-icon size="1em"><share /></el-icon> 
        <el-icon size="1em"><delete /></el-icon> 
        <el-icon size="1em"><search /></el-icon> 
    </div> 
</template>

… 说真的,我一万个难受

这玩意不能忍,之前看到 vant 的 icon 做的就很舒服

<van-icon name="chat-o" />

既然这样,那封装一个组件吧</

Vue3 项目中使用 Element Plus 的图标组件 `<el-icon-star-off>`,需要确保正确引入注册相关模块。 ### 安装依赖 首先,确保已经安装了 `element-plus` 其图标库 `@element-plus/icons-vue`: ```bash npm install element-plus @element-plus/icons-vue ``` ### 全局注册图标组件 如果希望全局使用图标组件,可以在 `main.js` 或 `main.ts` 中进行全局注册: ```javascript import { createApp } from &#39;vue&#39; import App from &#39;./App.vue&#39; import ElementPlus from &#39;element-plus&#39; import * as ElementPlusIconsVue from &#39;@element-plus/icons-vue&#39; const app = createApp(App) app.use(ElementPlus) // 注册所有图标组件为全局组件 for (const [key, component] of Object.entries(ElementPlusIconsVue)) { app.component(key, component) } app.mount(&#39;#app&#39;) ``` 完成上述步骤后,就可以直接在模板中使用 `<el-icon-star-off>` 组件[^1]: ```vue <template> <el-icon-star-off /> </template> ``` ### 局部注册图标组件 如果只需要在特定组件使用 `<el-icon-star-off>`,可以选择局部注册: ```vue <script setup> import { StarOff } from &#39;@element-plus/icons-vue&#39; </script> <template> <star-off /> </template> ``` 注意:Element Plus 图标组件的命名通常遵循 PascalCase 命名规范,但在模板中使用时会转换为 kebab-case。例如,`StarOff` 在模板中应写为 `<star-off />`。 ### 自定义封装图标组件 为了方便管理或扩展,可以创建一个封装组件来统一处理图标引用: ```vue <!-- components/CustomIcon.vue --> <script setup> import * as icons from &#39;@element-plus/icons-vue&#39; const props = defineProps({ name: { type: String, required: true } }) const iconComponent = icons[props.name] </script> <template> <component :is="iconComponent" /> </template> ``` 然后在其他组件使用封装组件: ```vue <template> <custom-icon name="StarOff" /> </template> <script setup> import CustomIcon from &#39;@/components/CustomIcon.vue&#39; </script> ``` 通过上述方法,可以灵活地在 Vue3 项目中使用 Element Plus 提供的 `<el-icon-star-off>` 图标组件,并根据需求选择合适的注册方式。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值