VUE3+element-plus 循环列表中图标由后台动态添加
vue3中,框架由element-plus搭建,需要在左侧菜单旁边添加图标,由后台传递内容进行动态添加
**
第一步:在main.js中引入所有的图标
**
// 引入所有图标
import * as ElementPlusIconsVue from ‘@element-plus/icons-vue’
// 全局注册所有图标,并存储图标名称到组件的映射表
const icons = {}
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component) // 注册为全局组件(如 )
icons[key] = component // 存储映射关系(用于动态组件)
}
// 将图标映射表挂载到全局,方便组件内使用
app.config.globalProperties.$icons = icons

**
第二步,在需要的界面引入
**
import { ref, onMounted, getCurrentInstance } from ‘vue’
// 获取全局注册的图标映射表
const { appContext } = getCurrentInstance();
const icons=appContext.config.globalProperties.icons = appContext.config.globalProperties.icons=appContext.config.globalProperties.icons;
// 根据图标名称获取对应的组件
const getIconComponent = (iconName) => {
// 容错处理:若图标不存在,返回默认图标(如 Warning)
return $icons[iconName] || $icons.Warning
}
在div中调用:


**
最终效果:
**

