html
复制代码
<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>