Nuxt3中Vuetify可展开表格异常问题求助
问题1:展开区域包含整行的原因及修复
你在expanded-row插槽里错误重复渲染了主行的所有列,还嵌套了<tr>标签(HTML规范里<tr>不能直接嵌套<tr>),导致展开后出现整行内容。expanded-row插槽的作用是仅渲染展开的额外内容行,不需要重复主行内容。
修正后的expanded-row模板:
<template v-slot:expanded-row="{ columns, item }" > <tr> <td :colspan="columns.length"> More info about {{ item.name }} </td> </tr> </template>
问题2:主行应用getColor函数的方法
主行的Calories列是默认渲染的,没有调用getColor逻辑,需要通过item.calories插槽自定义该列内容,把颜色规则应用上去:
在<v-data-table>内添加以下插槽:
<template v-slot:item.calories="{ item }"> <v-chip :color="getColor(item.calories)" size="small">{{ item.calories }}</v-chip> </template>
完整修正后的代码示例
<script setup> const headers = [ { title: 'Dessert (100g serving)', align: 'start', sortable: false, key: 'name', }, { title: 'Calories', key: 'calories' }, { title: 'Fat (g)', key: 'fat' }, { title: 'Carbs (g)', key: 'carbs' }, { title: 'Protein (g)', key: 'protein' }, { title: 'Iron (%)', key: 'iron' }, { title: '', key: 'data-table-expand'}, ] const desserts = [ { name: 'Frozen Yogurt', calories: 59, fat: 6.0, carbs: 24, protein: 4.0, iron: 1, }, { name: 'Ice cream sandwich', calories: 27, fat: 9.0, carbs: 37, protein: 4.3, iron: 1, }, // 其他数据... ] const expanded = [] const getColor = (calories) => { if (calories > 100) return 'red' else if (calories > 50) return 'orange' else return 'green' } </script> <template> <div> <v-main style="height: 88vh"> <v-sheet class="ml-4 mt-2"> <h1 class="ml-3 mt-3">Title</h1> <v-data-table :headers="headers" :items="desserts" :sort-by="[{ key: 'calories', order: 'asc' }]" v-model="expanded" item-value="name" show-expand > <template v-slot:top> <v-toolbar flat> <v-toolbar-title>Expandable Table</v-toolbar-title> </v-toolbar> </template> <!-- 自定义主行的Calories列,应用颜色逻辑 --> <template v-slot:item.calories="{ item }"> <v-chip :color="getColor(item.calories)" size="small">{{ item.calories }}</v-chip> </template> <!-- 修正后的展开行插槽,仅渲染额外内容 --> <template v-slot:expanded-row="{ columns, item }" > <tr> <td :colspan="columns.length"> More info about {{ item.name }} </td> </tr> </template> </v-data-table> </v-sheet> </v-main> </div> </template>
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

