Search code examples
vue.jsv-for

Vuejs nested foreach loop not working


I have the below HTML

<div id="app">
  <p>{{ message }}</p>
  <span v-for="word in words">
      {{word.name}} <br/>
      {{word.id}} <br/>
    <span v-for="mark in marks">
          {{mark}} 
    </span>
    <br/>
  </span>
</div>

I have the below script

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    words: [{
        id: 1,
        name: "sam",
        marks: [1, 2, 4]
      }, {
        id: 1,
        name: "name",
        marks: [1, 12, 3]
      }

    ]
  }

})

I am not getting the value of marks as expected.


Solution

  • It should be following, as mark is an element inside word:

    <div id="app">
      <p>{{ message }}</p>
      <span v-for="word in words">
          {{word.name}} <br/>
          {{word.id}} <br/>
        <span v-for="mark in word.marks">
              {{mark}} 
        </span>
        <br/>
      </span>
    </div>