DevonDahon
DevonDahon

Reputation: 8360

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.

Upvotes: 0

Views: 2987

Answers (2)

Blackraspberryyy
Blackraspberryyy

Reputation: 2134

You can add ref to the treeview, and use the updateAll(boolean) function of the v-treeview component.

<v-treeview
  :items="branches"
  :open-all="expanded"
  ref="myTreeview"
/>

<v-btn @click="toggleTreeview">
  <v-icon>{{ expanded ? 'mdi-arrow-collapse-all' : 'mdi-arrow-expand-all'}}</v-icon>
</v-btn>
<script>
export default {
  data() {
    return {
      expanded: true,
      branches: [...],
    }
  },
  methods: {
    toggleTreeview() {
      this.expanded = !this.expanded;
      this.$refs.mytreeview.updateAll(this.expanded); 
    },
  }
}
</script>

Here's a sample demo at codesandbox: enter image description here

Upvotes: 1

DevonDahon
DevonDahon

Reputation: 8360

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))
    },
}

Upvotes: 0

Related Questions