You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vuetify 3中为v-data-table行添加条件样式并保留自定义列插槽

在Vuetify 3中为v-data-table行添加条件CSS类并保留自定义列插槽

问题分析

当你使用#item默认插槽自定义整行时,会完全替换Vuetify默认的列渲染逻辑,导致你定义的#item.temperature、#item.humidity等自定义列插槽失效。要解决这个问题,需要使用Vuetify 3提供的#row插槽来单独自定义行元素,而不影响列的渲染逻辑。

解决方案

使用#row插槽来包裹行元素,在这个插槽中你可以为<tr>添加条件CSS类,同时保留所有自定义列插槽的功能。

修改后的代码示例

HTML部分

<v-data-table 
  :headers="tableHeaders"
  :items="tableItems"
  item-value="id"
>
  <!-- 自定义行插槽:添加条件类并保留默认行属性 -->
  <template #row="{ item, props }">
    <tr v-bind="props" :class="{'bg-red': item.temperature > 28}">
      <!-- 自动渲染列,包含自定义列插槽 -->
      <td v-for="header in tableHeaders" :key="header.key">
        <template v-slot:[`item.${header.key}`]="{ item }"></template>
      </td>
    </tr>
  </template>
      
  <!-- 温度列自定义插槽 -->
  <template #item.temperature="{item}">
    {{ item.temperature }} &deg;C
  </template>
  
  <!-- 湿度列自定义插槽 -->
  <template #item.humidity="{item}">
    {{ item.humidity }} %
  </template>

  <!-- 信息按钮列自定义插槽 -->
  <template #item.id="{item}">
    <v-btn @click="showInfo(item.id)">
      Show Info
    </v-btn>
  </template>
</v-data-table>

JavaScript部分

const tableHeaders = [
  {
    title: 'Temperature',
    sortable: true,
    key: 'temperature'
  },
  {
    title: 'Humidity',
    sortable: true,
    key: 'humidity'
  },
  {
    title: 'Info',
    sortable: false,
    key: 'id'
  },
]

const tableItems = [
  {
    id: 1,
    temperature: 22,
    humidity: 55
  },
  {
    id: 2,
    temperature: 30,
    humidity: 45
  },
  {
    id: 3,
    temperature: 22,
    humidity: 75
  },
]

// 示例方法
const showInfo = (id) => {
  console.log(`Showing info for item ${id}`)
}

关键说明

  1. #row插槽的作用:这个插槽专门用于自定义<tr>元素,接收item(当前行数据)和props(Vuetify默认的行属性,如选中状态类、行事件等),通过v-bind="props"可以保留组件的默认行为。
  2. 条件类的添加:直接在<tr>上通过:class绑定条件类,根据行数据动态判断样式。
  3. 保留自定义列插槽:<td>内的<template v-slot:[item.${header.key}]>会自动匹配你定义的#item.[key]插槽,无需手动编写列内容,既保留了自定义列的逻辑,又不会覆盖行的样式设置。
  4. 数据路径修正:你的原始代码中使用item.columns.temperature访问数据,但tableItems里并没有columns层级,直接使用item.temperature即可正确访问数据。

内容的提问来源于stack exchange,提问作者Ektor Makras

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 02:26:18