天天看點

element-ui table修改斑馬條紋顔色前言帶斑馬紋的表格修改斑馬條紋顔色頁面效果示例代碼結語

前言

最近在工作中用到了element-ui,修改table斑馬條紋顔色屬實是花了些時間。總結出來分享給大家,希望可以幫到有需要的人。

帶斑馬紋的表格

<el-table>

标簽上添

stripe

 屬性可以建立帶斑馬紋的表格。

stripe

 屬性預設是true。

<el-table stripe>
           

修改斑馬條紋顔色

首先,在

<el-table>

标簽上添加

row-class-name

屬性,

row-class-name

是清單行的回調方法,可以使用為所有行設定一個固定的 className。

<el-table stripe :row-class-name="onTableRowClassName">
           

row-class-name

屬性值可以是一個字元串也可以是函數

function({ row, rowIndex })

第一個參數

row

是目前行的資料, 第二個參數

rowIndex

是清單的目前行數。

注意:

row-class-name

是屬性不是方法,使用在

<el-table>

标簽上是

:row-class-name="xxx"

,而不是

@row-class-name="xxx"

然後,在綁定的方法中為偶數行(包含第0行)添加上對應的className;

const onTableRowClassName = ({row, rowIndex})=>{
    if (rowIndex%2==0) {
    return 'statistics-warning-row';
  } else {
    return '';
  }
}
           

最後,找到選擇器的位置,修改成想要的樣式即可。

.el-table__row.statistics-warning-row .cell {
    background: #00ff00;
  } 
           

頁面效果

示例代碼

<template>
  <el-table :data="tableData" stripe style="width: 100%" :row-class-name="onTableRowClassName">
    <el-table-column prop="date" label="Date" width="180" />
    <el-table-column prop="name" label="Name" width="180" />
    <el-table-column prop="address" label="Address" />
  </el-table>
</template>

<script lang="ts" setup>
const tableData = [
  {
    date: '2022-08-08',
    name: '張三',
    address: '北京市',
  },
    {
    date: '2022-08-08',
    name: '張三',
    address: '北京市',
  },
    {
    date: '2022-08-08',
    name: '張三',
    address: '北京市',
  },
    {
    date: '2022-08-08',
    name: '張三',
    address: '北京市',
  },
]
const onTableRowClassName = ({row, rowIndex})=>{
    if (rowIndex%2==0) {
    return 'statistics-warning-row';
  } else {
    return '';
  }
}
</script>

<style>
  .el-table .cell {
    color: #fff;
    background: #000000;
  }
  .el-table__row.statistics-warning-row .cell {
    background: #00ff00;
  } 
</style>
           

結語