Victor Oliveira
Victor Oliveira

Reputation: 1129

Nested loop in Vue

I have an object of objects that I am passing with vue and I am doing this to run:

 <ul>
    <li v-for="subjects in questions">
        <li v-for="question in subjects">
            @{{ question }}
        </li>
    </li>
</ul>

but I am getting this error:

Property or method "subjects" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in root instance)

How can I run a nested loop in vue?

Upvotes: 16

Views: 30023

Answers (2)

Sub S
Sub S

Reputation: 155

The accepted answer addresses arrays inside objects created as properties. I was looking for iterating simple multi dimensional arrays and it brought me to this page. So adding that answer as well for posterity:

new Vue({
  el: '#app',
  data: {
    questions: [
      ['test1.1', 'test1.2'],
      ['test2.1', 'test2.2']
    ]
  }
})
<script src="https://unpkg.com/vue"></script>

<div id='app'>

  <ol>
    <li v-for="subjects, index in questions">
      {{ index }}
      <ol type='I'>
        <li v-for="question in subjects">
          {{ question }}
        </li>
      </ol>
    </li>
  </ol>
</div>

IOW, the issue with the sample in the question is that there is a naked nested <li/> added inside parent <li/> without a sub-list grouping.

Upvotes: 1

Limon Monte
Limon Monte

Reputation: 54379

Here you go with the example:

var vm = new Vue({
  el: '#app',
  data: {
    questions: [
      {
        subjects: ['question 1.1', 'question 1.2']
      },
      {
        subjects: ['question 2.1', 'question 2.2']
      }
    ]
  }
})
<script src="https://cdn.jsdelivr.net/vue/2.0.3/vue.js"></script>

<div id="app">
  <ul>
    <li v-for="question in questions">
      <ul>
        <li v-for="subject in question.subjects">
          {{ subject }}
        </li>
      </ul>
    </li>
  </ul>
</div>

Upvotes: 23

Related Questions