You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue中借助unplugin-icons动态渲染Element Plus图标组件?

实现方法:从字符串数组动态生成Element Plus图标组件

由于unplugin-icons和unplugin-auto-import已经将i-ep-xxx格式的图标组件全局注册到Vue应用中,直接利用Vue的动态组件特性就能实现需求,核心是通过<component :is="组件名称字符串">渲染对应图标。

完整代码示例

<template>
  <!-- 遍历图标数组,批量渲染图标 -->
  <div class="icon-group">
    <el-icon 
      v-for="iconName in iconList" 
      :key="iconName"
      :size="24"
    >
      <component :is="iconName" />
    </el-icon>
  </div>
</template>

<script setup>
// 定义存储图标名称的数组
const iconList = ['i-ep-avatar', 'i-ep-cellphone', 'i-ep-apple']
</script>

关键注意事项

  • 确保unplugin-icons配置中已包含Element Plus图标集合,比如在Vite配置文件中:
    // vite.config.ts
    import Icons from 'unplugin-icons/vite'
    
    export default defineConfig({
      plugins: [
        Icons({
          collections: {
            ep: {} // 注册Element Plus图标集
          }
        })
      ]
    })
    
  • 数组中的字符串必须与自动导入的组件名完全匹配(i-ep-xxx格式),否则无法识别组件
  • 若需动态更新图标列表,直接修改iconList数组即可,Vue会自动响应式更新渲染结果

内容的提问来源于stack exchange,提问作者zzw6df7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 14:54:19