Change Vue Element UI table cell style based on value

Viewed 2902

I use Element UI. How can I change the color from the rate cell value? If rate < 0 then color is red, else color is green.

Maybe the table attribute cell-class-name can help me?

HTML

<el-table
    :data="tableData"
    style="width: 100%">
    <el-table-column
        prop="date"
        label="Date"
        width="180">
    </el-table-column>
    <el-table-column
        prop="name"
        label="Name"
        width="180">
    </el-table-column>
    <el-table-column
        prop="rate"
        label="Rate">
    </el-table-column>
</el-table>

JS

export default {
    data() {
        return {
            tableData: [{
                date: '2016-05-03',
                name: 'Tom',
                rate: 1
            }, {
                date: '2016-05-02',
                name: 'Tom',
                rate: -1
            }, {
                date: '2016-05-04',
                name: 'Tom',
                rate: 22
            }, {
                date: '2016-05-01',
                name: 'Tom',
                rate: -22
            }]
        }
    }
}
2 Answers

Bind a method to the cell-class-name prop of <el-table>:

<el-table
  :data="tableData"
  style="width: 100%"
  :cell-class-name="classChecker"
>

Define that classChecker method to test for the rate column and conditionally apply a class to the cell based on the value:

methods: {
  classChecker({ row, column }) {
    if (column.property === 'rate') {
      const val = row[column.property];
      if (val > 0 ) {
        return 'greenClass'
      } else {
        return 'redClass'
      }
    }
  }
}

CSS

.greenClass {
  background: green;
}
.redClass {
  background: red;
}

Use a columnn template

<el-table-column prop="rate" label="Rate">
      <template #default="scope">
          <label class="scope.row.rate < 0 ? 'danger' : 'success'">{{scope.row.rate}}</label>
      </template>
 </el-table-column>

Link

Edit:Link

Related