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>
相关推荐
|晴 天|6 分钟前
Vue 3 实战:打造可拖拽歌词、播放列表的嵌入式音乐播放器
前端·javascript·vue.js
Liu.7749 分钟前
Vue 3 开发中遇到的报错(2)
前端·javascript·vue.js
jerrywus27 分钟前
把 Obsidian 知识库接进 Claude Code:400 行代码实现 AI 长期记忆
前端·agent·claude
小t说说27 分钟前
2026年PPT生成工具评测及使用体验
大数据·前端·人工智能
雨季mo浅忆27 分钟前
第五项目梳理
前端·项目梳理
hERS EOUS37 分钟前
WebSpoon9.0(KETTLE的WEB版本)编译 + tomcatdocker部署 + 远程调试教程
前端
|晴 天|40 分钟前
Vue 3 实现实时通知系统:支持未读计数、红点提醒、一键已读
javascript·vue.js·ecmascript
前端那点事41 分钟前
Vue3 Tree-Shaking 原理解析
前端·vue.js
DROm RAPS1 小时前
SQL 实战:复杂数据去重与唯一值提取
前端·数据库·sql
爱怪笑的小杰杰1 小时前
uni-app Vue3 国际化最佳实践:告别应用重启,优雅实现多语言切换
前端·vue.js·uni-app