需求:要求实现单击改变单元行的背景颜色为#e6f7ff,鼠标移入移出的时候单元行的背景颜色为#fafafa(ant-design-vue组件库自带的颜色),并且鼠标移入的背景颜色不能掩盖单击单元行之后的背景颜色
实现:实现单击单元行改变背景颜色需要用到ant-design-vue提供的两个属性
rowClassName和customRow
<template>
<a-table
:columns="columns"
:data-source="data"
size="middle"
:pagination="pagination"
class="table"
:customRow="rowClick"
:rowClassName="setRowClassName"
>
</template>
<script setup>
import {ref} from 'vue'
const selectedRowKeys = ref([])//声明一个数组,在行点击函数里面用来存每一行数据的唯一标识id或者其//他参数
const rowClick = (record,index) => {
return {
onclick:(e)=>{
selectedRowKeys.value.length = 0//函数运行之初就清空数组是为了保证里面就只有一个参数,这样在点击单元行的时候就不会同时出现两个单元行因为单击而变色,两个单元行都变色,而是始终保持table里面只有一个单元行因为被单击而变色
selectedRowKeys.value.push(record.id) //将单击的该单元行的数据的唯一标识存入//selectedRowKeys 之中
}
}
}
const setRowClassName = (record, index) => {
//使用数组方法includes查看selectedRowKeys里面是否含有该唯一表示id,有则返回类名highlight
//该处返回的类名指的是给点击的单元行添加类名
if (selectedRowKeys.value.includes(record.id)) {
return "highlight";
} else {
return "";
}
};
</script>
<style scoped lang="scss">
/*点击单元行之后修改颜色*/
:deep .highlight {
background-color: #e6f7ff;
}
:deep .ant-table-tbody{
> .highlight:hover:not(.ant-table-expanded-row) > td,.ant-table-row-hover,.ant-table-row-hover>td{
background:none !important;
//这里是将鼠标移入时的背景色取消掉了
}
}
</style>