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>
相关推荐
老家的回忆2 分钟前
jsPDF和html2canvas生成pdf,组件用的elementplus,亲测30多页,20s实现
前端·vue.js·pdf·html2canvas·jspdf
半点寒12W6 分钟前
uniapp全局状态管理实现方案
前端
Vertira7 分钟前
pdf 合并 python实现(已解决)
前端·python·pdf
PeterJXL42 分钟前
Chrome 下载文件时总是提示“已阻止不安全的下载”的解决方案
前端·chrome·安全
hackchen1 小时前
从0到1解锁Element-Plus组件二次封装El-Dialog动态调用
前端·vue.js·elementui
用户7579419949701 小时前
Vue响应式原理推导过程
vue.js·响应式设计
君子宜耘心1 小时前
el-table虚拟列表封装
前端
黄瓜沾糖吃1 小时前
大佬们指点一下倒计时有什么问题吗?
前端·javascript
温轻舟1 小时前
3D词云图
前端·javascript·3d·交互·词云图·温轻舟
buibui1 小时前
打包一个工具类
前端