如何为v-data-table添加文本溢出省略号及行深色hover效果
Vuetify v-data-table 文本省略号与行hover效果问题
我使用Vuetify的v-data-table构建了一个5列表格,部分列已预设宽度,需要实现两个需求:
- 所有单元格文本最多显示一行,超出部分显示省略号,但尝试
text-overflow: ellipsis、white-space: nowrap等CSS属性后未生效,新闻列会自动加宽以容纳全部文本,省略号无法显示 - 实现表格行hover时背景加深的效果
相关代码如下:
表格代码
<v-data-table dark :footer-props="{ 'items-per-page-options': [10, 25, -1] }" dense calculate-widths fixed-header height="498" :headers="headers" hide-default-header :items="res" sort-by="publicationDate" :sortDesc="sortVal" > <template v-slot:header="{ props: { headers } }"> <thead> <tr> <th v-for="h in headers" :class="h.class" :key="h.text"> <span>{{h.text}}</span> </th> </tr> </thead> </template> <template #item.video="{ item }"> <a target="_blank" v-if="item.video != ''" class="links1 video-icon" :href="item.video" > <v-btn dark icon> <v-icon class="ic1">mdi-movie</v-icon> </v-btn> </a> </template> <template #item.title2="{ item }"> <a target="_blank" v-if="item.file != ''" class="links1" :href="item.file" > <span style="color:white"> {{ item.title }} </span> </a> </template> </v-data-table>
表头配置
headers: [ { text: "Source", value: "dataSource", width: "120px", class:"source-field"}, { text: "News", value: "title2", width: "214px", class:"news-field"}, { text: "Actors", value: "concernedActors", width: "242px" }, { text: "Video", value: "video", width: "58px" }, { text: "Publication", value: "publicationDate", width: "80px" }, ],
尝试的CSS代码
th.news-field{ max-width: 100px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
解决方案
一、修复文本省略号不生效问题
问题核心有两点:一是仅给表头th设置样式,未覆盖数据单元格td;二是calculate-widths属性会自动计算列宽,覆盖预设的宽度值。调整步骤如下:
- 移除
calculate-widths属性:从v-data-table标签中删除该属性,确保预设列宽生效 - 全局设置省略号样式:给表头和数据单元格都应用样式,同时确保自定义插槽内的元素继承省略号规则
修改后的CSS:
/* 表头单元格样式 */ .source-field, .news-field { width: inherit; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } /* 数据单元格样式,对应第1、2、3列 */ .v-data-table__tbody td:nth-child(1), .v-data-table__tbody td:nth-child(2), .v-data-table__tbody td:nth-child(3) { width: inherit; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } /* 自定义插槽内的链接元素,确保宽度100%并继承省略号样式 */ .links1 { display: block; width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
二、实现行hover背景加深效果
针对dark模式,添加行hover的背景样式:
/* 表格行hover时的背景加深效果 */ .v-data-table__tbody tr:hover { background-color: rgba(255, 255, 255, 0.1) !important; }
内容的提问来源于stack exchange,提问作者Quentin
相关产品推荐
相关产品推荐

