Element?Plus修改表格行和單元格樣式詳解
前言
實習工作需要根據表格的狀態(tài)字段來設置行的樣式,記錄一波。
先來一下基礎配置。(Vue3)
<template> <el-table :data="tableData" border style="width: 400px"> <el-table-column prop="name" label="姓名" width="100" /> <el-table-column prop="age" label="年齡" width="100" /> <el-table-column prop="job" label="工作" /> </el-table> </template> <script setup> const tableData = [ { name: "clz", age: 21, job: "Coder", }, { name: "czh", age: 21, job: "Coder", }, { name: "赤藍紫", age: 21, job: "Coder", }, ]; </script> <style lang="less" scoped> </style>
設置某一行的樣式
主要是通過 row-style屬性來實現。它是行的 style的回調方法,可以通過它來實現設置某一行的樣式。
先讓我們來體驗一下它的參數都是些什么。
<el-table style="width: 400px" border :data="tableData" :row-style="rowState" > </el-table>
const rowState = (arg) => { console.log(arg) }
可以發(fā)現,它是一個對象,一個屬性是行的數據,一個是行號(從0開始),至于不只是打印3次,而是打印9次的原因還沒發(fā)現,后面單元格的會打印18次,9個單元格打印18次。但是這個并不是本次的研究重點。
那么,我們怎樣能設置樣式呢?
只需要返回含有屬性樣式的對象即可。(駝峰命名法)
const rowState = (arg) => { return { backgroundColor: 'pink', color: '#fff' } }
然后在搭配參數使用,就能實現根據表格內容設置行的樣式。
const rowState = ({ row }) => { let style = {} switch (row.name) { case 'clz': style = { backgroundColor: 'red' } break; case 'czh': style = { backgroundColor: 'blue' } break; case '赤藍紫': style = { backgroundColor: 'purple' } break; } return style; }
設置某一個單元格的樣式
通過 cell-style屬性來實現。做法和上面一樣,就不多說了,主要的四個參數 row, column, rowIndex, columnIndex
。
- row:行的信息
- column:列的信息
- rowIndex: 行數(0開始算)
- columnIndex:列數(0開始算)
<el-table style="width: 400px" border :data="tableData" :cell-style="cellStyle" > </el-table>
const cellStyle = ({ row, column, rowIndex, columnIndex }) => { if (rowIndex === 1 && columnIndex === 1) { return { backgroundColor: 'pink' } } }
其實,cell-state不只是能設置單元格的樣式,因為它的參數中含有 row和 column,所以還可以用來設置某一行或某一列的樣式。
const cellStyle = ({ row, column, rowIndex, columnIndex }) => { if (column.label === '工作') { return { backgroundColor: 'purple' } } if (row.name === '赤藍紫') { return { backgroundColor: 'red' } } }
注意,這里重疊的地方并不會出現后來的樣式覆蓋掉前面的樣式,而是先到先得
表頭樣式修改(贈品)
特殊的表頭,特殊的處理
header-row-style:只有一個rowIndex屬性
const headerRowStyle = (args) => { console.log(args) return { height: '100px', backgroundColor: 'red' } }
發(fā)現只有標頭的行高有所變化,這是為啥呢?
檢查樣式發(fā)現,這是因為單元格本身具有背景顏色,所以并不會生效。
header-row-style:和正常的單元格一樣,有四個屬性
const headerCellStyle = ({ row, column, rowIndex, columnIndex }) => { if (columnIndex === 1) { return { backgroundColor: 'pink' } } }
也可以通過column屬性來設置符合條件的表頭單元格的樣式。
const headerCellStyle = ({ row, column, rowIndex, columnIndex }) => { ? if (column.label === '姓名') { return { backgroundColor: 'red' } } }
總結
到此這篇關于Element Plus修改表格行和單元格樣式的文章就介紹到這了,更多相關Element Plus修改單元格樣式內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
ant design vue datepicker日期選擇器中文化操作
這篇文章主要介紹了ant design vue datepicker日期選擇器中文化操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10