antdv table 自定义单元格显示

antdv table 自定义单元格显示

环境

  • vue-class-component 模式编写
  • typescript 4.7.3

一、 模板语法

    <a-table :data-source="aTableData" :columns="aTableColumns" >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex === 'name'">
          <span :style="{color: 'red'}" v-html="index + '.' + record.name"></span>
        </template>
      </template>
    </a-table>

效果

二、 customCell

修改column的对应列的customCell

  • customCell返回值的类型参考其使用typescript编写的声明文件中的 TdHTMLAttributes extends HTMLAttributes
   {
      title: 'customCell渲染',
      width: 80,
      dataIndex: 'time',
      customCell: function (record, rowIndex, column) {
        return {
          innerHTML: `<span style="color:blue">${record.time}</span>`
        }
      }
    }

三、 customRender

新建 TsxExt.tsx文件

export function renderAddress(data: { address: string }) {
  return <div style={{ color: 'pink' }}>
    {data.address}
  </div>
}

在目标vue文件中引入

import { renderAddress } from './TsxExt'

修改表格列的配置描述

    {
      title: 'customRender渲染',
      width: 80,
      dataIndex: 'address',
      customRender: function ({ record }) {
        return renderAddress(record)
      }
    }

相关代码

Example.vue
<template>
  <div class="example">
    <a-table :data-source="aTableData" :columns="aTableColumns">
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex === 'name'">
          <span :style="{color: 'red'}" v-html="index + '.' + record.name"></span>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts">
import { TableColumnType } from 'ant-design-vue'
import { Options, Vue } from 'vue-class-component'
import { renderAddress } from './TsxExt'

@Options({
  props: {}
})
export default class Example extends Vue {
  aTableData = [
    {
      name: '测试',
      time: '2022-01-01 00:00:00',
      address: '测试地址'
    }
  ]

  aTableColumns: TableColumnType[] = [
    {
      title: '模板语法渲染',
      width: 80,
      dataIndex: 'name'
    },
    {
      title: 'customCell渲染',
      width: 80,
      dataIndex: 'time',
      customCell: function (record, rowIndex, column) {
        return {
          innerHTML: `<span style="color:blue">${record.time}</span>`
        }
      }
    },
    {
      title: 'customRender渲染',
      width: 80,
      dataIndex: 'address',
      customRender: function ({ record }) {
        return renderAddress(record)
      }
    }
  ]
}
</script>
<style>
:deep(.example) {
  width: 100%;
}
</style>
TsxExt.tsx
export function renderAddress(data: { address: string }) {
  return <div style={{ color: 'pink' }}>
    {data.address}
  </div>
}

全部效果

image

posted @ 2022-09-02 09:54  闲一话  阅读(1771)  评论(0编辑  收藏  举报