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>
相关推荐
weixin_443478512 分钟前
flutter组件学习之对话框与提示详解
javascript·学习·flutter
lightqjx13 分钟前
【前端】前端学习一之HTML从入门到精通
前端·学习·html
Joyee69114 分钟前
RN 的事件调度 RuntimeScheduler
前端·react native
sensen_kiss41 分钟前
CAN302 电子商务技术 Pt.1 Web技术导论
前端·网络·学习
ProgramHan1 小时前
十大排行榜——前端语言及要介绍
前端
Patrick_Wilson1 小时前
你删过 lock 文件吗?聊聊包管理器迁移中 90% 的人会踩的坑
javascript·npm·前端工程化
早點睡3901 小时前
ReactNative项目OpenHarmony三方库集成实战:react-native-permissions
javascript·react native·react.js
氢灵子1 小时前
Fixed 定位的失效问题
前端·javascript·css
英俊潇洒美少年1 小时前
函数组件(Hooks)的 **10 大优点**
开发语言·javascript·react.js
haibindev1 小时前
把近5万个源文件喂给AI之前,我先做了一件事
java·前端·c++·ai编程·代码审计·架构分析