場景:給列表數據中,每行根據不同狀態顯示不同顏色。
官方教程使用table組件中的tableRowClassName屬性
<template> <el-table :data="tableData" style="width: 100%" :row-class-name="tableRowClassName"> <el-table-column prop="date" label="日期" width="180"> </el-table-column> <el-table-column prop="name" label="姓名" width="180"> </el-table-column> <el-table-column prop="address" label="地址"> </el-table-column> </el-table> </template> <style> .el-table .warning-row { background: oldlace; } .el-table .success-row { background: #f0f9eb; } </style> <script> export default { methods: { tableRowClassName({row, rowIndex}) { if (rowIndex === 1) { return 'warning-row'; } else if (rowIndex === 3) { return 'success-row'; } return ''; } }, data() { return { tableData: [{ date: '2016-05-02', name: '王小虎', address: '上海市普陀區金沙江路 1518 弄', }, { date: '2016-05-04', name: '王小虎', address: '上海市普陀區金沙江路 1518 弄' }, { date: '2016-05-01', name: '王小虎', address: '上海市普陀區金沙江路 1518 弄', }, { date: '2016-05-03', name: '王小虎', address: '上海市普陀區金沙江路 1518 弄' }] } } } </script>
在測試過程中,此方法沒有生效,百度了解到,需要使用全局屬性
在elementUI中,row-class-name、row-style、cell-class-name等屬性要想生效必須使用全局class才能生效。因為之前的代碼都是在組件中編寫的,所以去除<style scoped></style>中的scoped即可該組件中的樣式變為全局屬性。
試了下果然有效。
但是去掉scoped的話,scoped控制局部顯示樣式的,去掉的話,可能會與其他的頁面有重復。
在不去掉scoped的情況,可以選擇通過引用的方式。
單獨寫個css文件,寫入樣式
.el-table .warning-row { background-color: oldlace; } .el-table .success-row { background-color: #f0f9eb; }
通過引用的方式可達到全局的效果:
<style scoped> @import "../../styles/table_style.css"; .input { width: 170px; margin-left: 10px; } .btn { display: flex; margin-top: 10px; margin-left: 10px; } .tab { margin-top: 10px; margin-left: 20px; } </style>