一起养成写作习惯!这是我参加「掘金日新打算 · 4 月更文挑战」的第2天,点击查看流动详情。
简介
点赞 + 关注 + 珍藏 = 学会了
这是一篇对日常工作没什么帮忙的文章~
如果你还不太分明
Element Plus
的icon
是如何应用的,能够先浏览 《Element Plus 的 el-icon 到底怎么用》
Element UI
和 Element Plus
的 icon
用法是不一样的,在 Element Plus
中都改成了 svg
。
我在 《Element Plus 的 el-icon 到底怎么用》 里也比照过用法。
我习惯了 Element UI
的用法,但又喜爱用 Vue3
,所以就在 Element Plus
的根底上二次封装了一个语法有点像 Element UI
里 icon
的组件进去。
尽管在我日常的 Vue3
我的项目中不会用本文所讲的这个组件,但我还是要搞进去。因为我真的好闲。
设计
要实现的性能
- 通过
type
属性应用指定的svg
图标。 size
属性传入 number 或者 string 都行,Element Plus
只反对number
,所以用的时候须要v-bind:size="20"
这样写,或者用简写,但有时候还是会遗记加v-bind
,所以间接反对 size="20" 这样的字符串会更不便。type
属性反对首字母小写,Element Plus
应用的svg
是大驼峰格局的,但有些短的单词有时候真的会遗记首字母大写。color
属性间接照搬回Element Plus
的。
最终的应用形式
<e-icon type="Aim" :size="36" color="rgba(53, 131, 208, 0.5)" />
因为是二次封装,所以不能用回 <el-icon>
,这是 Element Plus
的组件。
本次封装的目标是简化 icon
的应用形式,所以我把标签名也跟着简化了,变成 <e-icon>
毛病
打包进去的体积可能会大一丢丢。
开发
开发中波及的技术点:
- 组件通信
- 动静组件
- 全量引入
Element Plus
提供的svg
图标
本文的例子次要应用 props
的形式进行组件通信。
如果你想理解更多 Vue3
的组件通信形式,能够浏览 《Vue3 过10种组件通信形式》
本例的代码比较简单,对应代码,跟着我的实现步骤来看。
以下是我的实现步骤:
- 全量引入
svg
图标 - 引入
icon
款式 - 接管父组件传入的
size
、color
和type
- 让
size
也兼容字符串类型(Element Plus
只反对number
) - 图标名称首字母转大写
- 通过中括号的形式动静获取
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 和 typeconst 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
点赞 + 关注 + 珍藏 = 学会了