element-ui 表格合并之后鼠標(biāo)hover效果
這次主要介紹行合并后的hover效果處理,由于element-ui合并行之后眼姐,鼠標(biāo)經(jīng)過時(shí)众旗,默認(rèn)只會(huì)高亮第一行,如下圖:
image.png
但實(shí)際我們想要的是,在鼠標(biāo)經(jīng)過這一合并行時(shí)律想,被合并的行都是高亮狀態(tài)绍弟,而不是只有第一行單元格高亮
image.png
通過查看表格組件的屬性發(fā)現(xiàn)晌柬,el-ui并沒有提供可以直接這樣實(shí)現(xiàn)的方法,但是我們發(fā)現(xiàn)年碘,有一個(gè)屬性row-class-name
,可以實(shí)現(xiàn)這種效果埃难。
具體實(shí)現(xiàn)思路如下:
給每條數(shù)據(jù)加一個(gè)order涤久,從1開始遞增,且將滿足合并行條件的數(shù)據(jù)的order設(shè)置為一樣的
鼠標(biāo)進(jìn)入事件判斷鼠標(biāo)進(jìn)入哪一個(gè)單元格考抄,遍歷數(shù)據(jù)蔗彤,將和該行的order相等的數(shù)據(jù)中的order以
this.cellIndex
變量保存起來在
rowClassName
方法中疯兼,遍歷數(shù)據(jù)吧彪,將每一行row
的order和上一步保存的order做對(duì)比姨裸,相等的情況下傀缩,給該行設(shè)置類名hover-row
鼠標(biāo)移開事件重置
this.cellIndex
以下是實(shí)現(xiàn)代碼
<template>
<el-table
:data="tableData"
style="width: 100%"
:span-method="objectSpanMethod" // 表格合并
:row-class-name="rowClassName" // 動(dòng)態(tài)給行添加樣式
@cell-mouse-enter="handleMouseEnter" // 單元格移入事件
@cell-mouse-leave="handleMouseLeave" // 單元格移出事件
>
<el-table-column
type="selection"
reserve-selection
width="55">
</el-table-column>
....
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [{
id: '12987122',
name: '王小虎',
amount1: '234',
amount2: '3.2',
amount3: 10
}, ...],
cellIndex: -1,
}
},
created() {
this.handleData();
},
methods: {
// 合并行
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) {
if (rowIndex % 2 === 0) {
return {
rowspan: 2,
colspan: 1
};
} else {
return {
rowspan: 0,
colspan: 0
};
}
}
},
// 處理數(shù)據(jù), 給每一條數(shù)據(jù)加order
handleData() {
let order = 1;
let data = this.tableData;
for (let i=0; i<data.length; i++) {
if(i === 0) {
data[i].order = order;
} else {
if (i % 2 === 0) {
// 此處是給相同的數(shù)據(jù)加相同order,具體判斷條件可根據(jù)自己數(shù)據(jù)進(jìn)行判斷
data[i]['order'] = data[i - 1]['order'] = data[i]['order']
? data[i]['order']
: order;
} else {
data[i]['order'] = order + 1;
}
}
}
}盛险,
// 鼠標(biāo)進(jìn)入單元格
handleMouseEnter(row, column, cell, event) {
this.tableData.forEach((item) => {
if (row.order === item.order) {
this.cellIndex = row.order;
}
})
},
// 給相應(yīng)的rowIndex添加類名
rowClassName({ row, rowIndex }) {
// console.log(row, rowIndex);
let r = -1;
this.tableData.forEach((item) => {
if (this.cellIndex === row.order) {
r = rowIndex;
}
});
if (rowIndex === r) {
return 'hover-row';
}
},
// 鼠標(biāo)離開
handleMouseLeave(row, column, cell, event) {
this.cellIndex = -1;
}
}
}
</script>