el-table固定为第一列设置背景颜色
时间: 2025-07-15 10:00:19 浏览: 11
在使用 `el-table` 时,若需要实现固定第一列并设置其背景颜色,可以通过以下方式完成:
### 固定第一列
通过 `el-table-column` 的 `fixed` 属性可以固定某一列。例如,将第一列的 `fixed` 设置为 `left`,即可将其固定到表格左侧:
```html
<el-table :data="tableData">
<el-table-column prop="id" label="ID" width="100" fixed="left"></el-table-column>
<!-- 其他列 -->
</el-table>
```
### 设置第一列的背景颜色
可以通过 `cell-style` 属性设置单元格的样式,根据 `columnIndex` 判断是否为第一列,并为其设置背景颜色:
```html
<el-table :data="tableData" :cell-style="cellStyle">
<el-table-column prop="id" label="ID" width="100" fixed="left"></el-table-column>
<!-- 其他列 -->
</el-table>
```
在脚本部分定义 `cellStyle` 方法:
```javascript
const cellStyle = (data) => {
if (data.columnIndex === 0) {
return { backgroundColor: '#F5F7FA' };
}
};
```
### 处理表头和悬停效果
如果希望表头也具有相同的背景颜色,可以通过 `header-cell-style` 设置表头单元格的样式:
```html
<el-table :data="tableData" :cell-style="cellStyle" :header-cell-style="headerCellStyle">
<el-table-column prop="id" label="ID" width="100" fixed="left"></el-table-column>
<!-- 其他列 -->
</el-table>
```
定义 `headerCellStyle` 方法:
```javascript
const headerCellStyle = (data) => {
if (data.columnIndex === 0) {
return { backgroundColor: '#F5F7FA' };
}
};
```
### 完整示例代码
以下是完整的代码示例:
```html
<template>
<el-table :data="tableData" :cell-style="cellStyle" :header-cell-style="headerCellStyle">
<el-table-column prop="id" label="ID" width="100" fixed="left"></el-table-column>
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
</el-table>
</template>
<script setup>
import { ref } from 'vue';
const tableData = ref([
{ id: 1, name: '张三', age: 25 },
{ id: 2, name: '李四', age: 30 },
]);
const cellStyle = (data) => {
if (data.columnIndex === 0) {
return { backgroundColor: '#F5F7FA' };
}
};
const headerCellStyle = (data) => {
if (data.columnIndex === 0) {
return { backgroundColor: '#F5F7FA' };
}
};
</script>
```
### 注意事项
- 如果发现固定列导致横向滚动条失效,可以通过 CSS 调整 `.el-table__fixed` 的高度和底部位置[^4]。
- 对于鼠标悬停时的背景色问题,可以通过自定义 CSS 样式进行调整[^3]。
通过以上方法,可以轻松地固定第一列并为其设置背景颜色,同时确保整体交互体验流畅。
阅读全文
相关推荐


















