1. 需求:
el-table 点击单元格,改变所在行和列的背景色,加粗显示交叉点文字;
2. 初始化表格,如下图:
3. 点击“湖南”单元格后,改变其所在行和列的背景颜色,加粗显示文字,如下图:
4. 代码如下:
<!--
* @Description: 点击单元格,改变当前所在行和列的样式
-->
<template>
<div class="wrap">
<el-table :data="tableData" border style="width: 100%;"
:row-class-name="tableRowClassName" @row-click="rowClick" :row-style="selectedRowStyle"
:cell-class-name="tableCellClassName" @cell-click="cellClick" :cell-style="selectedCellStyle"
>
<el-table-column align="center" prop="name" label="姓名"></el-table-column>
<el-table-column align="center" prop="sex" label="性别" ></el-table-column>
<el-table-column align="center" prop="age" label="年龄" ></el-table-column>
<el-table-column align="center" prop="area" label="地区" ></el-table-column>
<el-table-column align="center" prop="nation" label="民族" ></el-table-column>
</el-table>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [
{
name: '张一',
sex: '女',
age: '18',
area: '陕西',
nation: '汉族'
},
{
name: '张二',
sex: '男',
age: '29',
area: '宁夏',
nation: '回族'
},
{
name: '张三',
sex: '男',
age: '23',
area: '广西',
nation: '壮族'
},
{
name: '张四',
sex: '女',
age: '35',
area: '湖南',
nation: '苗族'
},
{
name: '张五',
sex: '女',
age: '27',
area: '陕西',
nation: '汉族'
}
],
// 行的索引值
getRowIndex: null,
// 列的索引值
getCellIndex: null
}
},
mounted() {
},
methods: {
// ------------- 点击单元格改变当前行和列的背景颜色 -------------
// ------------- 设置表格 行 相关的样式 -------------
// 为行对象(row)设置index属性
tableRowClassName({ row, rowIndex }) {
row.rowIndex = rowIndex;
},
// 行点击事件,这里获取到的行对象(row)是没有index属性的,索引值是初始化添加进去的
rowClick(row) {
this.getRowIndex = row.rowIndex;
},
// 设置行对象(row)的样式(style),只在文本显示时才有效果
selectedRowStyle({ row, rowIndex }) {
if (this.getRowIndex === rowIndex) {
return {
"background-color": "#f0f9eb"
};
}
},
// ------------- 设置表格 列 相关的样式 -------------
// 为列对象(cell)设置索引值
tableCellClassName({ column, columnIndex }) {
column.columnIndex = columnIndex;
},
// 列点击事件,这里获取到的列对象(column)是没有index属性的,索引值是初始化添加进去的
cellClick(row, column) {
this.getCellIndex = column.columnIndex;
},
// 设置列对象(cell)的样式(style),只在文本显示时才有效果
selectedCellStyle({ column, columnIndex, row, rowIndex }) {
if (this.getCellIndex === columnIndex) {
if(this.getRowIndex == rowIndex) {
return {
"background-color": "#f0f9eb !important",
"font-weight": "bold !important"
};
} else {
return {
"background-color": "#f0f9eb !important"
};
}
}
}
}
}
</script>
<style lang="scss">
.wrap {
// 去掉el-table的hover变色效果
// 方法1:此方法适用没有设置固定列时
.el-table tbody tr:hover>td {
background-color: transparent !important;
}
// 方法2:此方法适用设置了固定列fixed属性后
// .el-table__body .el-table__row.hover-row td{
// background-color: transparent !important;
// cursor: pointer;
// }
}
</style>