[Vuejs]-Temp variable inside a loop with Vue

0๐Ÿ‘

โœ…

I think we can achieve this by simply using recursion. You can set append links using the example below:

var items = [
{
  id: 1,
  level: 1,
  name: 'link 1',
  children: [],
  to: 'link1',
},
{
  id: 2,
  level: 1,
  name: 'link2',
  to: 'link2',
  children: [
    { id: 3, level: 2, name: 'link 3', to: 'link3' },
    {
      id: 4,
      level: 2,
      name: 'link 4',
      to: 'link4',
      children: [
        { id: 5, level: 3, name: 'link 5', to: 'link5'},
        { id: 6, level: 3, name: 'link 5', to: 'link5'},
      ],
    }
  ]
}
];


const getItems = () => {
this.items = this.items.map(x=> {
    if(x.children && x.children.length) {
    x.children = getPopulatedChildren(x.children, x.to);
  }
  return x;
});
console.log(this.items);
return this.items;
}

Option 1: If you want to combine the link with parent only. For example for link 5 it would be something like link4/link5 then getPopulatedChildren would be

const getPopulatedChildren = (children, to) => {
  return children.map(x=> {
    if(x.children && x.children.length) {
      x.children = getPopulatedChildren(x.children, x.to);
    }
    return {...x, to: to+'/'+x.to}; 
  });
}

Option 2: If you want to combine the link with all the parents. For example for link 5 it would be something like link2/link4/link5 then getPopulatedChildren would be

const getPopulatedChildren = (children, to) => {
    return children.map(x=> {
    x.to = to+'/'+x.to;
    if(x.children && x.children.length) {
        x.children = getPopulatedChildren(x.children, x.to);
    }
    return x; 
  });
}

Make sure to update the Tree view and call getItems function to get the Items with updated link

<v-treeview
  :items="getItems()"
  item-key="name"
  dense
  hoverable
  open-on-click
  hide-details="true"
>
  <template
    slot="label"
    slot-scope="{ item }"
  >
    <nuxt-link
      :to="item.to"
      class="menu-item"
    >
      {{ item.name }}
    </nuxt-link>
  </template>
</v-treeview>

Leave a comment