Vue Element table表格合并(动态)

在项目开发过程中,会遇到合并表格的情况,这里针对第一列的重复数据进行合并展示

在这里插入图片描述

页面代码
<el-table
  :data="dataList"
  :span-method="handleSpanMethod"
  border
>
 <el-table-column label="班级" align="center" prop="className" />
 <el-table-column label="姓名" align="center" prop="name" />
 <el-table-column label="年龄" align="center" prop="age" />
</el-table>
JS代码实现
data() {
    
    
    return {
    
    
    	spanArr: [], // 遍历数据时,根据相同的标识去存储记录
      	pos: 0,
    	dataList: [
			{
    
    className: '高一三班', name: '张三', age: 18 },
			{
    
    className: '高一三班', name: '张无忌', age: 19 },
			{
    
    className: '高一六班', name: '王五', age: 18 },
			{
    
    className: '高一七班', name: '赵六', age: 19 },
			{
    
    className: '高一八班', name: '杜画', age: 20 },
		]
    }
},
created() {
    
    
   this.getSpanArr(this.dataList);
},
methods: {
    
    
	//表格合并单元格跨行,实现首列根据不同类型进行跨行
	 getSpanArr(data) {
    
    
	   this.spanArr = [];
	   this.pos = 0;
	   //遍历数据
	   data.map((item, index) => {
    
    
	     //判断是否是第一项
	     if (index == 0) {
    
    
	       this.spanArr.push(1);
	       this.pos = 0;
	     } else {
    
    
	       //不是第一项时,就根据标识去存储
	       if (data[index].className === data[index - 1].className) {
    
    
	         // 查找到符合条件的数据时每次要把之前存储的数据+1
	         this.spanArr[this.pos] += 1;
	         this.spanArr.push(0);
	       } else {
    
    
	         // 没有符合的数据时,要记住当前的index
	         this.spanArr.push(1);
	         this.pos = index;
	       }
	     }
	   });
	 },
	//得到行、列的合并值
	handleSpanMethod({
     
      row, column, rowIndex, columnIndex }) {
    
    
	 // 页面列表上 表格合并行 -> 第几列(从0开始)
	 // 需要合并多个单元格时 依次增加判断条件即可
	 if (columnIndex === 0) {
    
    
	   // 二维数组存储的数据 取出
	   const _row = this.spanArr[rowIndex];
	   const _col = _row > 0 ? 1 : 0;
	   return {
    
    
	     rowspan: _row,
	     colspan: _col,
	   };
	   //不可以return {rowspan:0, colspan: 0} 会造成数据不渲染, 也可以不写else,eslint过不了的话就返回false
	 } else {
    
    
	   return false;
	 }
	},
}

猜你喜欢

转载自blog.csdn.net/sunshineTing2/article/details/130623011
今日推荐