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>

效果图:

效果图
ZhangApple
更多

发布时间:2024年03月21日

本文作者:ZhangApple。转载请注明并附上本文链接

评论一下

评论列表