NaiveUI表格中,实现动态合并单元格相同的数据

在NaiveUI表格中设定列的 colSpanrowSpan 来控制单元格行列的合并。

// 定义表格列
const columns = ref([ {
    title: "姓名",
    key: "name",
    rowSpan: (rowData, rowIndex) => {
      return 2;  //每两行合
    },
  },
  { title: "年龄", key: "ID" },
  { title: "地址", key: "address"},
]);

要实现每列相同的数据动态合并,我们可以定义一个函数getLastIndex,用于获取相同名称的最后一行的索引,之后在rowSpan中使用该方法,以下是完整代码:

<template>
  <div>
    <n-card>
      <n-data-table
        :columns="columns"
        :data="data"
        :pagination="false"
        :single-line="false"
      />
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";

// 定义数据源
const data = ref([
  { ID: 1, name: "苹果1", age: 1, address: "www.zhangpingguo.com" },
  { ID: 2, name: "苹果1", age: 2, address: "www.zhangpingguo.com" },
  { ID: 3, name: "苹果2", age: 3, address: "www.zhangpingguo.com" },
  { ID: 4, name: "苹果1", age: 4, address: "www.zhangpingguo.com" },
  { ID: 5, name: "苹果1", age: 5, address: "www.zhangpingguo.com" },
  { ID: 6, name: "苹果1", age: 7, address: "www.zhangpingguo.com" },
  { ID: 7, name: "苹果2", age: 7, address: "www.zhangpingguo.com" },
  { ID: 8, name: "苹果2", age: 7, address: "www.zhangpingguo.com" },
  { ID: 9, name: "苹果2", age: 7, address: "www.zhangpingguo.com" },
  { ID: 10, name: "苹果2", age: 7, address: "www.zhangpingguo.com" },
  { ID: 11, name: "苹果2", age: 8, address: "www.zhangpingguo.com" },
  { ID: 12, name: "苹果3", age: 8, address: "www.zhangpingguo.com" },
  { ID: 13, name: "苹果3", age: 8, address: "www.zhangpingguo.com" },
  { ID: 14, name: "苹果4", age: 8, address: "www.zhangpingguo.com" },
]);

// 定义一个函数,用于获取相同名称的最后一行的索引
const getLastIndex = (index, names, types) => {
  const sameNameIndex = data.value.slice(index).findIndex((item) => {
    return names.some((name, i) => item[types[i]] !== name);
  });
  return sameNameIndex === -1 ? data.value.length : sameNameIndex;
};

// 定义表格列
const columns = ref([
    {
    title: "姓名",
    key: "name",
    rowSpan: (rowData, rowIndex) => {
      return getLastIndex( rowIndex, [rowData.name], ["name"]);
    },
  },
  { title: "年龄", key: "ID", rowSpan: (rowData, rowIndex) => {
      return getLastIndex( rowIndex, [ rowData.name,rowData.age], [ "name","age"]);
    }, },
  { title: "地址", key: "address"},
]);
</script>

<!-- 定义样式 -->
<style scoped>

</style>

效果图:

更多信息请访问:张苹果博客

posted @ 2024-03-21 16:46  张苹果博客  阅读(98)  评论(0编辑  收藏  举报