使用 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) {
     app.component(transElIconName(key), Icons[key])   
   } 
} 

// 此处是借鉴(抄袭)一位大佬的写法,勿喷 
// https://blog.csdn.net/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) 
app.component('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>

完成

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

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐