1. 程式人生 > 實用技巧 >el-table合併單元格

el-table合併單元格

el-table合併單元格

合併效果

http://yangyushu.gitee.io/demo-element-table-cell-merge/

demo地址

https://gitee.com/yangyushu/demo-element-table-cell-merge

程式碼片段

methods: {
		/**
		 * 封裝--合併單元格--合併列
		 * 本方法引數參照
		 * https://element.eleme.cn/#/zh-CN/component/table
		 */
		verticalMerger({
			row,
			column,
			rowIndex,
			columnIndex
		}) {
			if (row[column.property]) { // 空值不合並
				if (columnIndex > 0) { // 不合並第一列
					return this.whetherVertical(column.property, row[column.property], rowIndex)
				}
			}
		},
		/**
		 * 呼叫--獲取合併列個數
		 * @param {String} key 當前單元格key
		 * @param {String} value 當前單元格value
		 * @param {Number} site 當前單元格下標
		 */
		whetherVertical(key, value, site) {
			const list = this.tableData // 獲取當前頁所有資料
			// 如果該資料下標不為0並且與上一格相同,該單元格被合併
			if (site > 0 && list[site - 1][key] === value) {
				return [0, 0]
			}
			// 獲取當前單元格合併個數,如果下一格不同,則返回1
			const num = this.getVerticalSum(key, value, list, site, 1)
			return [num, 1]
		},
		/**
		 * 遞迴--查詢合併列數量
		 * @param {String} key 當前引數key
		 * @param {String} value 當前引數value
		 * @param {Array} list 當前查詢集合
		 * @param {Number} site 當前所在下標
		 * @param {Number} sum 合併個數(遞迴增加)
		 */
		getVerticalSum(key, value, list, site, sum) {
			// 是否下一項存在
			if (list[site + 1]) {
				// 判斷下一項是否符合條件
				if (list[site + 1][key] === value) {
					return this.getVerticalSum(key, value, list, site + 1, sum + 1)
				} else {
					return sum
				}
			} else {
				return sum
			}
		},
		/**
		 * 封裝--合併單元格--合併行
		 */
		horizontalMerger({
			row,
			column,
			rowIndex,
			columnIndex
		}) {
			if (row[column.property]) { // 空值不參與合併
				const sub = this.horiKeys.findIndex(item => item === column.property)
				// 判斷當前單元格是否在合併keys中
				if (sub !== -1) {
					return this.whetherHorizontal(row[column.property], sub, this.horiKeys, rowIndex)
				}
			}
		},
		/**
		 * 呼叫--獲取合併行個數
		 * @param {String} value 單元格value
		 * @param {Number} sub 單元格key所在keys集合的下標
		 * @param {Array} keys 參與合併的keys集合
		 * @param {Number} rowIndex 當前資料所在行數(下標)
		 */
		whetherHorizontal(value, sub, keys, rowIndex) {
			const list = this.tableData // 獲取當前頁所有資料
			// 如果上一項存在並和該項相同,則該單元格被合併
			if (sub > 0 && list[rowIndex[keys[sub - 1]]] === value) {
				return [0, 0]
			}
			const num = this.getHorizontalSum(value, list[rowIndex], keys, sub, 1)
			return [1, num]
		},
		/**
		 * 遞迴--查詢合併數量
		 * @param {String} value 單元格value
		 * @param {list} data 當前行資料
		 * @param {String} keys 需要合併key集合
		 * @param {Number} sub 單元格key在key集合中的下標
		 * @param {Number} sum 合併個數(遞迴增加)
		 */
		getHorizontalSum(value, data, keys, sub, sum) {
			if (keys[sub + 1]) {
				if (data[keys[sub + 1]] === value) {
					return this.getHorizontalSum(value, data, keys, sub + 1, sum + 1)
				} else {
					return sum
				}
			} else {
				return sum
			}
		}
	}