Search code examples
treeviewvuetify.js

How to collapse a v-treeview with a button in Vuetify?


How to collapse a treeview with a button ?

I tried this:

<v-btn @click="expanded ? (expanded = false) : (expanded = true)"
    ><v-icon>{{
        expanded ? 'mdi-arrow-collapse-all' : 'mdi-arrow-expand-all'
    }}</v-icon></v-btn
>
<v-treeview
    :items="branches"
    :open-all="expanded"
/>
<script>
export default {
    data() {
        return {
            expanded: true,
            branches: [...],
        }
    }
}
</script>

But I can't get the open-all prop working.


Solution

  • I finally fixed my issue like below, opening only the first depth.

    First, I changed the button in the <template> to:

    <v-btn @click="toggleTreeview()"
        ><v-icon>{{
            open.length
                ? 'mdi-arrow-collapse-all'
                : 'mdi-arrow-expand-all'
        }}</v-icon>
    </v-btn>
    

    Then, I'm using these props to the <v-treeview>:

    <v-treeview
        :items="branches"
        item-key="id"
        :open.sync="open"
    />
    

    I removed expanded and add open array:

    <script>
    export default {
        data() {
            return {
                branches: [...],
                open: []
            }
        }
    }
    </script>
    

    Finally, I'm using this method to toggle the treeview (in other words, fill or empty the open array):

    methods: {
        toggleTreeview() {
            this.open.length
                ? (this.open = [])
                : this.branches.forEach((element) => this.open.push(element.id))
        },
    }