如何将Vuetify v-data-table展开箭头移至最左侧列
Vuetify v-data-table 展开箭头移至最左侧实现方案
核心修改思路
- 移除默认的
show-expand属性,避免右侧自动生成展开箭头 - 在表头数组最前端添加自定义展开列
- 通过插槽自定义展开图标,并实现展开/收起的状态切换逻辑
修改后的完整代码
<template> <v-data-table v-model:expanded="expanded" :headers="dessertHeaders" :items="desserts" item-value="name" > <template v-slot:top> <v-toolbar flat> <v-toolbar-title>Expandable Table</v-toolbar-title> </v-toolbar> </template> <!-- 自定义展开列的内容 --> <template v-slot:item.expand="{ item }"> <v-icon @click="toggleExpand(item)" class="cursor-pointer" > {{ expanded.includes(item.name) ? 'mdi-chevron-down' : 'mdi-chevron-right' }} </v-icon> </template> <template v-slot:expanded-row="{ columns, item }"> <tr> <td :colspan="columns.length"> More info about {{ item.name }} </td> </tr> </template> </v-data-table> </template> <script> export default { data() { return { expanded: [], dessertHeaders: [ // 新增:最左侧的自定义展开列 { title: '', key: 'expand', sortable: false, align: 'center' }, { 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' }, // 移除:原来的右侧展开列配置 ], desserts: [ { name: 'Frozen Yogurt', calories: 159, fat: 6.0, carbs: 24, protein: 4.0, iron: 1, }, { name: 'Ice cream sandwich', calories: 237, fat: 9.0, carbs: 37, protein: 4.3, iron: 1, }, { name: 'Eclair', calories: 262, fat: 16.0, carbs: 23, protein: 6.0, iron: 7, }, { name: 'Gingerbread', calories: 356, fat: 16.0, carbs: 49, protein: 3.9, iron: 16, }, { name: 'KitKat', calories: 518, fat: 26.0, carbs: 65, protein: 7, iron: 6, }, ], } }, methods: { // 切换展开/收起状态 toggleExpand(item) { const itemKey = item.name if (this.expanded.includes(itemKey)) { this.expanded = this.expanded.filter(key => key !== itemKey) } else { this.expanded = [...this.expanded, itemKey] } } } } </script>
关键说明
- 自定义展开列:在
dessertHeaders最前端添加key为expand的列,用于承载展开图标 - 状态切换逻辑:通过
toggleExpand方法手动维护expanded数组,判断当前行是否已展开,执行添加/移除操作 - 图标切换:根据
expanded数组是否包含当前行的name(item-value指定的唯一标识),切换展开/收起图标 - 展开行适配:展开行的
colspan使用columns.length,自动适配当前表头列数,无需手动修改
内容的提问来源于stack exchange,提问作者user2611
相关产品推荐
相关产品推荐

