实例
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>表格合并</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<body>
<div id="app">
<template>
<div>
<h5>列合并</h5>
<table border="1">
<tr>
<td colspan="2">1</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
</table>
<h5>行合并</h5>
<table border="1">
<tr>
<td rowspan="2">1</td>
<td>2</td>
</tr>
<tr>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
</table>
<h5>假动态列合并</h5>
<table border="1">
<tr v-for="index in 3" :key="index">
<template v-for="item in 2">
<td :key="item" v-if="colspanMerge[index-1][item-1]" :colspan="colspanMerge[index-1][item-1]">{{index}}-{{item}}</td>
</template>
</tr>
</table>
<h5>假动态行合并</h5>
<table border="1">
<tr v-for="index in 3" :key="index">
<template v-for="item in 2">
<td :key="item" v-if="rowspanMerge[index-1][item-1]" :rowspan="rowspanMerge[index-1][item-1]">{{index}}-{{item}}</td>
</template>
</tr>
</table>
<h5>动态合并</h5>
<el-table :data="data" :span-method="arraySpanMethod" border>
<el-table-column align="center" type="index"></el-table-column>
<el-table-column label="姓名" align="center" prop="name"></el-table-column>
<el-table-column label="购买物品" align="center" prop="wp"></el-table-column>
<el-table-column label="金额" align="center" prop="amount"></el-table-column>
</el-table>
</div>
</template>
</div>
</body>
<script>
const vm = new Vue({
el: '#app',
data() {
return {
rowspanMerge: [[2,1],[0,1],[1,1]],
colspanMerge: [[2,0],[1,1],[1,1]],
spanArr: [],
pos: 0,
data: [
{
name: '王三',
wp: '牙刷',
amount: 10
},
{
name: '王三',
wp: '牙膏',
amount: 22
},
{
name: '叶红',
wp: '毛巾',
amount: 30
},
{
name: '赵四',
wp: '可乐',
amount: 2.5
},
{
name: '赵四',
wp: '鸭脖',
amount: 50
}
]
}
},
created() {
this.getSpanArr()
},
methods: {
// 合并
getSpanArr() {
this.spanArr = []
for (let i = 0; i < this.data.length; i++) {
if (i === 0) {
this.spanArr.push(1)
this.pos = 0
} else if (this.data[i].name === this.data[i - 1].name) {
this.spanArr[this.pos] += 1
this.spanArr.push(0)
} else {
this.spanArr.push(1)
this.pos = i
}
}
},
arraySpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex<2) {
const _row = this.spanArr[rowIndex]
const _col = _row > 0 ? 1 : 0
return {
rowspan: _row,
colspan: _col
}
}
}
}
})
</script>
</html>
|