Vuetify 3.3.x How to click-to-expand row and call API and collapse all expanded rows when reload

1.2k views Asked by At

I have two question while using v-data-table in Vuetify 3.3.x. I have googled but all answers are for Vuetify 2.x, not suitable for Vuetify 3.3.x.

Here are my questions:

  1. When click Next Page or Previous Page, if there is any expanded row in data table, close all of them.

  2. When click a row, call function getRandomAnswer(null) and print it to the expanded row.

  3. When I click a row, how come all slots are expanded ? My code is very similar to the sample of official page (https://vuetifyjs.com/en/components/data-tables/basics/

For question 1 and 2, initially, I was trying to find relevant events in

<template v-slot:expanded-row="{ columns, item, isExpanded, toggleExpand }">

so that it would be very easy to make it. Unfortunatelly there is no such event in the slot. So, what can I do ?

Sample code

1

There are 1 answers

1
Moritz Ringler On

In Vuetify 3, DataTable has an :item-value prop, which should identify a property on the item objects giving a unique value for each item (in your case item-value="city" would make sense). The default value is id.

Vuetify tracks which rows are expanded through an array containing the item values of all expanded rows (i.e. ['TOKYO', TAIPEI] would correspond to the first two rows being expanded in your example).

Since you are not setting an item-value and your items do not have an id property, the item value for every item is undefined. When you expand a row, undefined is pushed to the array, which matches every item, so all rows are expanded. This is what the documentation means with:

Just like selection, row items require a unique property on each item for expansion to work. The default is id, but you can use the item-value prop to specify a different item property.

and on the selection page:

For the selection feature to work, the data table must be able to differentiate each row in the data set. This is done using the item-value prop. It designates a property on the item that should contain a unique value. By default the property it looks for is id.

You can also supply a function, if for example the unique value needs to be a composite of several properties. The function receives each item as its first argument.


Use v-model:expanded="..." to two-way bind to the array with the expanded items, or use the :expanded prop and @update:expanded event individually.

After you have set the :item-value and put an array into v-model:expanded you can:

  • empty the array on pagination events (probably not necessary after setting item-value)
  • push an item value to the array after getRandomAnswer() finished

Does that answer your question?