关于前端:二次封装elicon

5次阅读

共计 2310 个字符,预计需要花费 6 分钟才能阅读完成。

一起养成写作习惯!这是我参加「掘金日新打算 · 4 月更文挑战」的第 2 天,点击查看流动详情。

简介

点赞 + 关注 + 珍藏 = 学会了

这是一篇对日常工作 没什么帮忙 的文章~

如果你还不太分明 Element Plusicon 是如何应用的,能够先浏览《Element Plus 的 el-icon 到底怎么用》

Element UIElement Plusicon 用法是不一样的,在 Element Plus 中都改成了 svg

我在《Element Plus 的 el-icon 到底怎么用》里也比照过用法。

我习惯了 Element UI 的用法,但又喜爱用 Vue3,所以就在 Element Plus 的根底上二次封装了一个语法有点像 Element UIicon 的组件进去。

尽管在我日常的 Vue3 我的项目中不会用本文所讲的这个组件,但我还是要搞进去。因为我真的好闲。

设计

要实现的性能

  1. 通过 type 属性应用指定的 svg 图标。
  2. size 属性传入 number 或者 string 都行,Element Plus 只反对 number,所以用的时候须要 v-bind:size="20" 这样写,或者用简写,但有时候还是会遗记加 v-bind,所以间接反对 size=”20″ 这样的字符串会更不便。
  3. type 属性反对首字母小写,Element Plus 应用的 svg 是大驼峰格局的,但有些短的单词有时候真的会遗记首字母大写。
  4. color 属性间接照搬回 Element Plus 的。

最终的应用形式

<e-icon type="Aim" :size="36" color="rgba(53, 131, 208, 0.5)" />

因为是二次封装,所以不能用回 <el-icon>,这是 Element Plus 的组件。

本次封装的目标是简化 icon 的应用形式,所以我把标签名也跟着简化了,变成 <e-icon>

毛病

打包进去的体积可能会大一丢丢。

开发

开发中波及的技术点:

  1. 组件通信
  2. 动静组件
  3. 全量引入 Element Plus 提供的 svg图标

本文的例子次要应用 props 的形式进行组件通信。

如果你想理解更多 Vue3 的组件通信形式,能够浏览《Vue3 过 10 种组件通信形式》

本例的代码比较简单,对应代码,跟着我的实现步骤来看。

以下是我的实现步骤:

  1. 全量引入 svg图标
  2. 引入 icon 款式
  3. 接管父组件传入的 sizecolortype
  4. size 也兼容字符串类型(Element Plus 只反对 number
  5. 图标名称首字母转大写
  6. 通过中括号的形式动静获取 svg图标
<template>
  <ElIcon :size="size2Number" :color="color">
    <!-- 动静组件 -->
    <component :is="currentIcon"></component>
  </ElIcon>
</template>

<script>
export default {name: 'EIcon'}
</script>

<script setup>
import {computed} from 'vue'
import {ElIcon} from 'element-plus'
import * as Icons from '@element-plus/icons-vue' //【步骤 1】全量引入 svg 图标
import 'element-plus/es/components/icon/style/css' //【步骤 2】全量引入 svg 图标

//【步骤 3】接管父组件传入的 size、color 和 type
const props = defineProps({
  size: { // 图标尺寸
    type: [Number, String],
    default: 14,
    validator(value) {return !isNaN(value)
    }
  },
  color: { // 图标色彩
    type: String,
    default: 'inherit'
  },
  type: { // 图标类型
    type: String,
    default: ''
  }
})

//【步骤 4】size 转换成数值型
const size2Number = computed(() => {if (isNaN(props.size)) {return 20}
  return Number(props.size)
})

//【步骤 6】动静获取图标
const currentIcon = computed(() => {
  let iconType = props.type
  let icon = null

  if (iconType !== '') {
    //【步骤 5】首字母大写
    icon = iconType.replace(iconType[0],iconType[0].toUpperCase())
  }

  return Icons[icon] // 通过中括号的形式动静获取
})
</script>

做这类组件,我通常会给组件一个 name,能够看到下面的代码是有 name 的,并且这个 script 没加 setup

<script>
export default {name: 'EIcon'}
</script>

应用

在页面中引入并应用

<template>
  <div>
    <EIcon type="Aim" :size="36" color="rgba(53, 131, 208, 0.5)" />
  </div>
</template>

<script setup>
import EIcon from '@/components/EIcon/index.vue'
</script>

你也能够在 main.js 里 通过 app.use 全局注册该组件。

举荐浏览

👍《Element Plus 的 el-icon 到底怎么用?》

👍《Vue3 过 10 种组件通信形式》

👍《Vue3 递归组件》

👍《Vite 搭建 Vue2 我的项目(Vue2 + vue-router + vuex)》

本例代码在这:e-icon

点赞 + 关注 + 珍藏 = 学会了

正文完
 0