原始表格数据
要实现动态排名上升和下降的学生本次排名的字体样式,效果如下:
思路:
使用elementUI 表格的cell-style或者cell-class-name。在回调函数里判断排名。再返回样式或者样式类名。
实现代码如下:
<template>
<el-table
:data="tableData"
border
style="width: 500px"
:cell-class-name="getCellStyleClassName">
<el-table-column
prop="name"
label="姓名"
width="180">
</el-table-column>
<el-table-column
prop="lastRank"
label="上次排名"
width="180">
</el-table-column>
<el-table-column
prop="curRank"
label="本次排名">
</el-table-column>
</el-table>
</template>
<script>
export default {
name: "Table1",
data() {
return {
tableData: [{
name: '张三',
lastRank: 10,
curRank: 8
}, {
name: '李四',
lastRank: 3,
curRank: 5
}, {
name: '王五',
lastRank: 6,
curRank: 9
}, {
name: '赵丽',
lastRank: 8,
curRank: 5
}]
}
},
methods: {
// 使用cell-style, 直接返回样式 需要在el-table 标签上加上 :cell-style="setCellStyle"
// setCellStyle({row, column, rowIndex, columnIndex}) {
// console.log(rowIndex, columnIndex, row.name);
// if (columnIndex === 2) {
// if (row.lastRank < row.curRank) {
// // row.curRank = row.curRank + "↑";
// return {
// color: 'red',
// }
// } else if (row.lastRank > row.curRank) {
// // row.curRank = row.curRank + "↓";
// return {
// color: 'blue'
// }
// }
// }
// },
// 返回样式类名的方式(推荐做法)
getCellStyleClassName({row, column, rowIndex, columnIndex}) {
if (columnIndex === 2) {
if (row.lastRank < row.curRank) {
return 'progressed';
} else if (row.lastRank > row.curRank) {
return 'fall'
}
}
}
}
}
</script>
<!-- 注意这里不能加 scoped 否则样式不生效!!-->
<style>
.progressed {
color: red;
}
.progressed div::after {
content: '↑';
}
.fall {
color: blue;
}
.fall div::after {
content: '↓';
}
</style>
注意点:
1. elementUI 表格是表头行和表内容行是分开的。也就是说表头行是本来就有的,写了el-table-column 就有。数据行是从第二行开始的。也就是数据行的行索引是从第二行开始从0开始计数。
2. 使用 cell-class-name 时要把 style标签里的scoped 给去掉,否则写的样式不生效。
3. 注意伪类选择器的使用方法
.progressed div::after {
content: '↑';
}
表示在 progressed 类中的 div标签的后面加上上箭头 ↑