DRJ
DRJ

Reputation: 51

How to add treeview nodes with a single add node button in Vue Vuetify?

I am making a treeview component in vue/vuetify that allows the user to add custom-named nodes. I am able to have this work by having a "add node" button next to each child. However, this gets kind of messy after awhile. I would prefer to have a single "add node" button outside of the treeview. This is where it gets tricky. When I have it inline with the node, I can pass the node as an "item" to my add node function. As follows.

<v-treeview
  v-model="tree"
  :open="open"
  :items="items"
  item-key="name"
>
  <template v-slot:prepend="{ item}">
    <v-btn
      v-if="!item.file"
      color="primary"
      class="ma-2"
      dark
      @click="addFolder(item)"
    >add folder</v-btn>
  </template>
</v-treeview>

<script>
data: () => ({
selectedFile: null,
dialog: false,
dialog2: false,
location: "",
nextId: 0,
open: ["public"],
files: {
  pdf: "mdi-file-pdf"
},
tree: [],
items: [
  {
    name: "Minnesota"
  }
],

editedItem: {
  id: "",
  name: "",
  file: ""
},

editedIndex: -1
}),
addFolder(item) {
  this.editedIndex = this.items.indexOf(item);
  this.editedItem = item;
  this.dialog2 = true;
},

addChildFolder() {
  if (!this.editedItem.children) {
    this.$set(this.editedItem, "children", []);
  }

  const name = this.location;
  const id = this.nextId++;
  this.editedItem.children.push({
    id,
    name
  });
  this.dialog2 = false;
},
</script>

Since I am no longer able to attach the {item} to the node button, I need a way of clicking the row/node and then clicking the "add node" button, which is now outside of the treeview. Vuetify has an "Activatable" prop, but that just highlights the row. I need a way of saving the clicked node as a variable and using that in the "add node" button.

I'm sure this is all very confusing. Here is a codepen that hopefully makes it clear what I am trying to do. Thanks!

https://codepen.io/denisj/pen/WNQNKGa

Upvotes: 1

Views: 2463

Answers (1)

rd3n
rd3n

Reputation: 4560

Based on your codepen code, you must add .sync to the :active property of your v-treeview, so this.active will be set when you click on a tree node (or unset when you unselect a selected node):

https://codepen.io/rd3n/pen/PoPqWWj

Note that you can also add return-object to the v-treeview to get the complete object selected instead of just its key.

Upvotes: 1

Related Questions