Glenn Pierce
Glenn Pierce

Reputation: 950

Collapse or expand Groups in vuetify 2 data-table

I have a table where I have a number of items shown all grouped by a string property. By default these groups are all expanded.

https://vuetifyjs.com/en/components/data-tables/#grouped-rows

Is there anyway to collapse all the groups or expand them at once ?

Ie have a collapse all button above the table. I have search but can't find a solution.

Thanks

Upvotes: 3

Views: 7540

Answers (3)

David
David

Reputation: 101

Vuetify 2 has an undocumented data property on v-data-table called "openCache", which is an object keyed by the group value you are using to group your items. If you slap a ref on the data table, you can toggle the isOpen state for the group by setting the value for the corresponding group to true/false. By default they will all be true.

<v-data-table ref="table">...</v-data-table>
afterMyItemsHaveLoaded() {
   Object.keys(this.$refs.table.openCache).forEach(g => this.$refs.table.openCache[g] = false)
}

Upvotes: 1

Glenn Pierce
Glenn Pierce

Reputation: 950

Codeply-er answer may work but I didn't want to track $refs for each group. In the end I add this hack

private expandAll() {
    const self = this;

    for (const name of Object.keys(self.$refs.expandableTable.openCache)) {
        self.$refs.expandableTable.openCache[name] = true;
    }
}

private collapseAll() {
    const self = this;

    for (const name of Object.keys(self.$refs.expandableTable.openCache)) {
        self.$refs.expandableTable.openCache[name] = false;
    }
}

This probably relies on an internal method openCache so not ideal.

Upvotes: -4

Carol Skelly
Carol Skelly

Reputation: 362630

The latest Vuetify does pass the isOpen and toggle values in the group.header slot. You could customize this slot to track $refs for each group that can then be bound to a toggle all (or expand/collapse all) function....

  <template v-slot:group.header="{ group, headers, toggle, isOpen }">
        <td :colspan="headers.length">
            <v-btn @click="toggle" small icon :ref="group">
                <v-icon v-if="isOpen">mdi-chevron-up</v-icon>
                <v-icon v-else>mdi-chevron-down</v-icon>
            </v-btn>
            {{ group }}
        </td>
  </template>

  methods: {
    toggleAll () {
        Object.keys(this.$refs).forEach(k => {
            this.$refs[k].$el.click()
        })
    }
  }

Demo: https://codeply.com/p/ys4Df2OLiE

Upvotes: 9

Related Questions