How to use nested for loop in vue.js?

by hal.littel , in category: Javascript , 6 months ago

How to use nested for loop in vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 6 months ago

@hal.littel 

To use nested for loop in Vue.js, you can follow these steps:

  1. Create a Vue instance in your JavaScript code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
new Vue({
  el: '#app',
  data: {
    items: [
      { id: 1, name: 'Item 1' },
      { id: 2, name: 'Item 2' },
      { id: 3, name: 'Item 3' }
    ]
  }
});


  1. In your HTML code, use the v-for directive to loop through the outer array:
1
2
3
4
5
6
7
8
9
<div id="app">
  <div v-for="item in items" :key="item.id">
    {{ item.name }}

    <div v-for="nestedItem in item.nestedItems" :key="nestedItem.id">
      {{ nestedItem.name }}
    </div>
  </div>
</div>


  1. In your Vue instance, make sure to add the nestedItems property to each item in the outer array:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
new Vue({
  el: '#app',
  data: {
    items: [
      { id: 1, name: 'Item 1', nestedItems: [
        { id: 1, name: 'Nested Item 1' },
        { id: 2, name: 'Nested Item 2' }
      ] },
      { id: 2, name: 'Item 2', nestedItems: [
        { id: 3, name: 'Nested Item 3' },
        { id: 4, name: 'Nested Item 4' }
      ] },
      { id: 3, name: 'Item 3', nestedItems: [
        { id: 5, name: 'Nested Item 5' },
        { id: 6, name: 'Nested Item 6' }
      ] }
    ]
  }
});


In the above example, we have a nested array nestedItems inside each item of the items array. The outer loop (v-for="item in items") iterates over each item, and within that, the inner loop (v-for="nestedItem in item.nestedItems") iterates over each nested item. Each item and nested item can be accessed using the double curly braces {{ item.name }} and {{ nestedItem.name }}.