Nested loop in Vue

╄→尐↘猪︶ㄣ 提交于 2020-05-08 06:57:28

问题


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?


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/40029856/nested-loop-in-vue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!