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

Vue.js+Vuetify如何根据数据表行内值切换对应图标与行背景色?

调整步骤

  1. 给v-data-table组件添加item-class属性,用于动态绑定每行的背景样式类,该属性接收一个函数,参数为当前行数据,直接返回对应政党的类名即可。
  2. 使用v-data-table的自定义列插槽,重写Party列的渲染逻辑,根据政党值展示对应的图标。

修改后完整代码

<template>
  <v-card>
    <v-card-title>
      <v-text-field
        v-model="search"
        append-icon="mdi-magnify"
        label="Search"
        single-line
        hide-details
      ></v-text-field>
    </v-card-title>
    <v-data-table
      :headers="headers"
      :items="politicians"
      :search="search"
      :item-class="item => item.party"
    >
      <!-- 自定义Party列的渲染内容 -->
      <template #item.party="{ item }">
        <v-icon
          :icon="item.party === 'Democrat' ? 'mdi-donkey' : 'mdi-elephant'"
          class="mr-1"
        ></v-icon>
        {{ item.party }}
      </template>
    </v-data-table>
  </v-card>
</template>

<script>
export default {
  name: 'dashboard',
  data(){
    return{
      search: '',
      headers: [
        {
          align: 'start'
        },
        {text: 'Position', value: 'position'},
        {text: 'Name', value: 'name'},
        {text: 'Party', value: 'party'}
      ],
      politicians: [
        {
            name: "John Smith",
            party: "Democrat",
            position: "County Executive"
        },
        {
            name: "Bob Bush",
            party: "Republican",
            position: "County Executive"
        },
        {
            name: "Elaina Krasinsky",
            party: "Democrat",
            position: "District Attorney"
        },
        {
            name: "Robert Parson",
            party: "Republican",
            position: "District Attorney"
        }
    ],
    }
  },
}
</script>

<style scoped>
/* 用::v-deep提高权重,覆盖Vuetify默认行样式 */
::v-deep .Democrat{
  background-color: blue !important;
  color: #fff;
}
::v-deep .Republican {
   background-color: red !important;
   color: #fff;
}
</style>

版本兼容说明

如果使用的是Vuetify 2.x版本,v-icon的写法调整为<v-icon>{{ item.party === 'Democrat' ? 'mdi-donkey' : 'mdi-elephant' }}</v-icon>即可,其他逻辑不变。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 08:06:05