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

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

Posted by: admin November 26, 2021 Leave a comment

Questions:

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

Answers:

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>

###

Nesting p tags is not allowed in HTML

Vue compiler (which processes your template) somehow knows this and compiles into something like this:

<p v-for="entry in user">
    {{entry.name}}
    {{entry.session[0].name}}
</p>
<p v-for="session_entry in entry.session">
    {{session_entry.name}}
</p>

…which leads to an error "entry is undefined but referenced during render"

You can check yourself by pasting your templete into vue-compiler-online and look at the AST on the right

BTW you should always check your browsers Dev Tool console for useful messages like this when something doesn’t work as expected…