Vue3 封装 element-plus 图标选择器

一、实现效果

二、实现步骤

2.1. 全局注册 icon 组件

复制代码
// main.ts
import App from './App.vue';
import { createApp } from 'vue';
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

const app = createApp(App);

// 全局挂载和注册 element-plus 的所有 icon
app.config.globalProperties.$icons = []
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.config.globalProperties.$icons.push(key)
    app.component(key, component)
}

app.mount('#app');

2.2. 组件实现

复制代码
<script setup lang="ts">
import { ComponentInternalInstance, defineEmits, defineProps, getCurrentInstance } from 'vue'

const { appContext: {app: { config: { globalProperties } } } } = getCurrentInstance() as ComponentInternalInstance

interface Props {
  modelValue: string
}
const props = defineProps<Props>()

const emits = defineEmits(['update:modelValue'])
</script>

<template>
  <el-popover trigger="focus" :width="256">
    <template #reference>
      <el-button :icon="modelValue">{{ modelValue }}</el-button>
    </template>
    <div class="el-icon-picker">
      <component v-for="icon in globalProperties.$icons" :key="icon"
        :class="[icon, 'icon', { 'icon-active': icon == modelValue }]"
        :is="icon"
        @click="emits('update:modelValue', icon)">
      </component>
    </div>
  </el-popover>
</template>

<style scoped>
.el-icon-picker {
  height: 256px;
  overflow-y: scroll;
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}

.icon {
  display: inline-block;
  width: 24px;
  height: 24px;
  color: var(--el-text-color-regular);
  font-size: 20px;
  border-radius: 4px;
  cursor: pointer;
  text-align: center;
  line-height: 45px;
  margin: 5px;
}

.icon:hover {
  color: var(--el-color-primary);
}

.icon-active {
  color: var(--el-color-primary);
}
</style>

2.3. 使用

复制代码
<script setup lang="ts">
import { ref } from 'vue';
import ElIconPicker from './components/el-icon-picker.vue';

const icon = ref<string>('');
</script>

<template>
  <el-form>
    <el-form-item label="图标">
      <ElIconPicker v-model="icon"></ElIconPicker>
    </el-form-item>
  </el-form>
</template>
相关推荐
白云~️3 分钟前
table表格合并,循环渲染样式
javascript·vue.js·elementui
Hilaku5 分钟前
JavaScript 里的 !0、!1 到底是啥?聊聊那些压缩器最爱的“极简写法”
前端·javascript
全栈陈序员14 分钟前
前端文件下载常用方式详解
前端·javascript·chrome·ajax·css3·html5·safari
二十一_22 分钟前
🤖✨ ChatGPT API深度体验:让AI看懂图片、听懂语音、调用你的代码
前端·chatgpt·openai
Developer_Niuge29 分钟前
前端批量请求失败重复弹窗的正确解决方案
前端
前端小饭桌29 分钟前
告别嵌套地狱:用数据结构优化解决 JS 多层循环的混乱与静默错误
前端·javascript
爱摸鱼的格子31 分钟前
🚀 你真的会用 Promise.all 吗?10 个实用技巧助你成为异步处理大师!
前端
JacksonGao32 分钟前
React Fiber的调度算法你了解多少呢?
前端·react.js
这可不简单34 分钟前
方便易懂的自适应方案---echarts和dom样式大小自适应
前端·vue.js·echarts
玲小珑36 分钟前
Auto.js 入门指南(七)定时任务调度
android·前端