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>
相关推荐
凤凰战士芭比Q40 分钟前
web中间件——(二)Nginx(高级功能、优化)
前端·nginx·中间件
阿珊和她的猫43 分钟前
表单数据验证:HTML5 自带属性与其他方法的结合应用
前端·状态模式·html5
谷粒.2 小时前
Cypress vs Playwright vs Selenium:现代Web自动化测试框架深度评测
java·前端·网络·人工智能·python·selenium·测试工具
Hy行者勇哥3 小时前
HTML5 + 原生 CSS + 原生 JS 网页实现攻略
javascript·css·html5
小飞侠在吗7 小时前
vue props
前端·javascript·vue.js
DsirNg9 小时前
页面栈溢出问题修复总结
前端·微信小程序
小徐_23339 小时前
uni-app 也能远程调试?使用 PageSpy 打开调试的新大门!
前端·微信小程序·uni-app
大怪v9 小时前
【Virtual World 03】上帝之手
前端·javascript
用户841794814569 小时前
vxe-gantt 甘特图实现产品进度列表,自定义任务条样式和提示信息
vue.js
招来红月10 小时前
记录JS 实用API
javascript