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>
相关推荐
bonechips5 分钟前
LLM 的无状态:从 HTTP 协议到对话上下文工程
前端·javascript
杨利杰YJlio6 分钟前
Codex桌面客户端上手:项目、插件与自动化实战
前端·后端
胡志辉6 分钟前
从 prototype 到 V8,看懂 JavaScript 原型链
前端·javascript
ricardo19736 分钟前
React 渲染优化:memo / useMemo / useCallback 的正确姿势与并发模式实战
前端·面试
ClouGence8 分钟前
零代码自动化测试:手把手教你录出一条能反复用的测试用例
前端·测试
skiyee12 分钟前
🔥UniApp 仅需 5 行代码!实现所有页面中控制应用主题变化
前端·微信小程序
LaiYoung_13 分钟前
🎁 送你一套超好用超实用的 FE AI-Coding Skills
前端·人工智能·开源
幼儿园技术家32 分钟前
实现 GEO 监控:从多引擎探测到优化闭环
前端·后端
甲维斯32 分钟前
GLM5.2+ZCode复刻坦克大战,自测50万帧!
前端·ai编程·游戏开发
Csvn1 小时前
useRef 的 5 个冷门但救命的高级用法
前端