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

Vue3实现Easy-data-table每行显示不同图标

在Vue3的Easy-data-table中实现每行显示不同图标

核心思路是给每行数据绑定专属图标标识,再通过表格的自定义渲染能力(render函数或插槽)根据标识渲染对应图标,以下是具体实现方案:

1. 准备带图标标识的数据源

首先确保表格数据中每条记录都包含对应图标的标识(比如组件名、类名):

const tableData = [
  { id: 1, name: '项目A', iconType: 'Folder' },
  { id: 2, name: '项目B', iconType: 'Document' },
  { id: 3, name: '项目C', iconType: 'User' }
]

2. 方案一:使用render函数自定义列渲染

借助Easy-data-table的render属性,根据每行的iconType渲染对应图标组件(以Element Plus图标为例):

<template>
  <EasyDataTable
    :columns="tableColumns"
    :data="tableData"
  />
</template>

<script setup>
import { ref, h } from 'vue'
import { Folder, Document, User } from '@element-plus/icons-vue'
import EasyDataTable from 'easy-data-table'
import 'easy-data-table/dist/style.css'

// 表格数据源
const tableData = ref([
  { id: 1, name: '项目A', iconType: 'Folder' },
  { id: 2, name: '项目B', iconType: 'Document' },
  { id: 3, name: '项目C', iconType: 'User' }
])

// 图标映射表:将标识对应到组件
const iconComponentMap = {
  Folder,
  Document,
  User
}

// 列配置
const tableColumns = ref([
  {
    field: 'iconType',
    label: '图标',
    // 自定义渲染函数
    render: (row) => {
      const TargetIcon = iconComponentMap[row.iconType]
      return h(TargetIcon, { size: 18, color: '#409eff' })
    }
  },
  { field: 'name', label: '项目名称' },
  { field: 'id', label: 'ID' }
])
</script>

3. 方案二:使用列插槽渲染(更直观)

Easy-data-table支持按column-{field}命名的插槽,直接在模板中渲染对应图标:

<template>
  <EasyDataTable
    :columns="tableColumns"
    :data="tableData"
  >
    <!-- 对应iconType字段的列插槽 -->
    <template #column-iconType="{ row }">
      <component :is="iconComponentMap[row.iconType]" size="18" />
    </template>
  </EasyDataTable>
</template>

<script setup>
import { ref } from 'vue'
import { Folder, Document, User } from '@element-plus/icons-vue'
import EasyDataTable from 'easy-data-table'
import 'easy-data-table/dist/style.css'

const tableData = ref([
  { id: 1, name: '项目A', iconType: 'Folder' },
  { id: 2, name: '项目B', iconType: 'Document' },
  { id: 3, name: '项目C', iconType: 'User' }
])

const iconComponentMap = {
  Folder,
  Document,
  User
}

const tableColumns = ref([
  { field: 'iconType', label: '图标' },
  { field: 'name', label: '项目名称' },
  { field: 'id', label: 'ID' }
])
</script>

适配其他图标库

如果使用Font Awesome等类名式图标库,只需调整图标渲染逻辑:

  1. 数据源改为存储类名:{ id:1, name:'项目A', iconClass:'fa-solid fa-folder' }
  2. 渲染时直接绑定类名:
<template #column-iconClass="{ row }">
  <i :class="row.iconClass" style="font-size:18px"></i>
</template>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 09:15:30