有一個展示內容的表格,會有合並行的需求,應用了Element UI 的table。
Element UI 提供了如下的方法,能夠實現跨行
通過給table
傳入span-method
方法可以實現合並行或列,方法的參數是一個對象,里面包含當前行row
、當前列column
、當前行號rowIndex
、當前列號columnIndex
四個屬性。該函數可以返回一個包含兩個元素的數組,第一個元素代表rowspan
,第二個元素代表colspan
。 也可以返回一個鍵名為rowspan
和colspan
的對象。
=== Element UI ===
<el-table :data="tableData" :span-method="objectSpanMethod" border style="width: 100%; margin-top: 20px">
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) {
if (rowIndex % 2 === 0) { //當行rowIndex % 2 === 0 的時候 實現跨行
return {
rowspan: 2,
colspan: 1
};
} else {
return {
rowspan: 0,
colspan: 0
};
}
}
現在后端返回的數據是一個數組:
最終實現的效果:
也就是根據category返回值的不同,第一列跨行數也不一樣。
分析:第一列跨的行數,正是每個category的數目長度。跨行的rowIndex開始值可以是遍歷數組當每個category一組的開始的第一個index值。
所以
1. 遍歷后端返回的數組每一項,利用數組的findIndex 方法,可以找到第一次就滿足條件的Index,即為開始的rowIndex.
2. 遍歷得到每一個category 所對應的具體的長度。即為跨幾行
// 獲取到后端數據
getDataList () { if (!this.dataListLoading) { this.dataListLoading = true; this.$http.get(`接口url`) .then((data) => { if (data.code === 0) { this.dataList = data.data || [] // 獲取每個類目下的條數 let arr = [] // let indexList = [] this.dataList.forEach(ele => { let firstIndex = this.dataList.findIndex(item => { return item.category === ele.category // 當category相同的時候,返回第一個相同的Index 賦值給 firstIndex }) if (arr.findIndex(item => { return item.firstIndex === firstIndex }) === -1) { arr.push({ length: this.dataList.filter(item => { return item.category === ele.category //利用數組的filter方法,過濾出相同category的數組的長度。數組長度-即為跨多少行 }).length, firstIndex: firstIndex // firstIndex 返回的是第一個catergory就滿足的第一個Index,即為rowIndex開始於第幾行。 }) } }) // arr = new Set(arr) // console.log(arr) this.indexInfoList = arr // 得到的arr里面的內容:Array(3) // 0 : firstIndex : 0; length: 4 1: firstIndex: 4 length:5 console.log(arr) } else { this.$message.error(data.msg || '查詢失敗') this.dataList = [] this.indexInfoList = [] } }) .catch(e => { this.dataList = [] this.indexInfoList = [] }) .finally(() => { this.dataListLoading = false; }); } },
objectSpanMethod({ row, column, rowIndex, columnIndex }) { if (columnIndex === 0) { let index = this.indexInfoList.findIndex(item => { //遍歷數組 return item.firstIndex === rowIndex }) if (index > -1) { return { rowspan: this.indexInfoList[index].length, colspan: 1 } } else { return { rowspan: 0, colspan: 0 } } } }