15

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?

Limon Monte
  • 52,539
  • 45
  • 182
  • 213
Victor Oliveira
  • 1,109
  • 1
  • 12
  • 29

2 Answers2

21

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>
Limon Monte
  • 52,539
  • 45
  • 182
  • 213
1

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.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
  • Your answer was helpful. One thing that is urk'ing me about the original question, is the way the element is named in both the nested v-for loop and the parent v-for loop. The singular element out of a collection of subjects would likely be 'subject'. And the singular element out of a collection of questions would likely be question. I know this maps to how the original question's v-for loops were written though. – CaffeinateOften Jun 23 '18 at 17:17