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>
相关推荐
念九_ysl16 分钟前
前端循环全解析:JS/ES/TS 循环写法与实战示例
前端·javascript·typescript
anyup_前端梦工厂2 小时前
了解几个 HTML 标签属性,实现优化页面加载性能
前端·html
前端御书房3 小时前
前端PDF转图片技术调研实战指南:从踩坑到高可用方案的深度解析
前端·javascript
2301_789169543 小时前
angular中使用animation.css实现翻转展示卡片正反两面效果
前端·css·angular.js
风口上的猪20154 小时前
thingboard告警信息格式美化
java·服务器·前端
程序员黄同学4 小时前
请谈谈 Vue 中的响应式原理,如何实现?
前端·javascript·vue.js
爱编程的小庄5 小时前
web网络安全:SQL 注入攻击
前端·sql·web安全
宁波阿成5 小时前
vue3里组件的v-model:value与v-model的区别
前端·javascript·vue.js
柯腾啊5 小时前
VSCode 中使用 Snippets 设置常用代码块
开发语言·前端·javascript·ide·vscode·编辑器·代码片段
Jay丶萧邦5 小时前
el-select:有关多选,options选项值不包含绑定值的回显问题
javascript·vue.js·elementui