失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > element-plus的el-icon和@element-plus/icons vue3 组件封装与使用

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

时间:2019-11-24 08:12:18

相关推荐

element-plus的el-icon和@element-plus/icons 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" />

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

element团队的意思很明显,就是按需加载

那咱们就退而求其次,一次加载完,在src/目录下创建plugins(如果已有的兄弟姐妹请无视)

然后,在这个文件夹中引入 icons 所有组件,并且全部注册进去

import * as Icons from '@element-plus/icons' export default (app) => {for (const key in Icons) {ponent(transElIconName(key), Icons[key]) } } // 此处是借鉴(抄袭)一位大佬的写法,勿喷 // /Alloom/article/details/119415984 function transElIconName(iconName) {return 'vue' + iconName.replace(/[A-Z]/g, (match) => '-' + match.toLowerCase()) }

然后在main.js文件内注册

import { createApp } from 'vue' import App from './App.vue' const app = createApp(App) // code ... // 使用icons elementPlusIcons(app)

然后核心的部分来了:

在components文件夹中创建一个组件(组件名字随便取),我这里暂且叫HyIcon

这里核心的方法是 vue3 的新方法 resolveComponent,根据组件名动态引入已加载的组件,具体请参照:全局 API | Vue.js

<script> import { h, resolveComponent, defineComponent } from 'vue' export default defineComponent({props: {name: {type: String,required: true}},render() {return <el-icon {...this.$attrs}>{h(resolveComponent(this.name))}</el-icon>}}) </script>

引入方法如下:

1. 全局引入(main.js)

import { createApp } from 'vue' import App from './App.vue' import HyIcon from '@/components/HyIcon'const app = createApp(App) // code ... // 使用icons elementPlusIcons(app) ponent('HyIcon', HyIcon)

2. 局部引入(具体组件):

<template><hy-icon size="100" color="red" name="vue-add-location" /></template><script>import { defineComponent, defineAsyncComponent } from 'vue' export default defineComponent({components: {HyIcon: defineAsyncComponent(() => import('@/components/HyIcon'))}})</script>

上面用到了 vue 的defineAsyncComponent方法

也可以这么用:

<template><hy-icon size="100" color="red" name="vue-add-location" /></template><script> import { defineComponent, defineAsyncComponent } from 'vue' import { HyIcon } from '@/components/HyIcon' export default defineComponent({components: { HyIcon } })</script>

完成

如果小伙伴们有好点的建议或者意见,可以提给我,我会及时改进,欧了,古德拜!

如果觉得《element-plus的el-icon和@element-plus/icons vue3 组件封装与使用》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。