Search code examples
htmlvue.jsvuejs2vue-componentv-for

Nested v-for loops using p tag doesn't work in Vue.js


I want to nest 2 v-for loops. It should be quite simple, but it's not working and I have no clue why.

When I loop through the users and display their names, this is working fine. When I take the first element from the session-array and display it's name, this is also working fine.

However, when I want to cycle through the session-array in a nested v-for loop, the array seems to be empty. Why is this?

<p v-for="entry in user">
    {{entry.name}} //this is working fine
    {{entry.session[0].name}} //this is also working fine, so "session" is an array with elements that have the property "name"
    <p v-for="session_entry in entry.session"> //this v-for is not executed, as if entry.session would be empty
        {{session_entry.name}}
    </p>
</p>
  data: {
    user: [{
      name: 'test2name', 
      session:[
        {name:'sessionname'},
        {name:'sessionname2'}
      ]
    }]
  }

According to this code snippet it should be working. What did I miss? https://www.codegrepper.com/code-examples/javascript/vuejs+nested+v-for


Solution

  • When i change the outer p to div it works fine as below :

    Vue.config.devtools = false;
    Vue.config.productionTip = false;
    
    new Vue({
      el: '#app',
      data: {
        user: [{
          name: 'test2name',
          session: [{
              name: 'sessionname'
            },
            {
              name: 'sessionname2'
            }
          ]
        }]
      }
    })
    <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
    
    
    <div id="app" class="container">
      <div v-for="entry in user">
        {{entry.name}}
        <p v-for="session_entry in entry.session">
          {{session_entry.name}}
        </p>
      </div>
    </div>