Continue loop in a v-for loop

Is there a way to continue a loop if conditions aren’t met?

Something similar to:

<div v-for="eventGroups in res">
  <div v-if="eventGroups.length == 0">
    <!-- continue for loop -->
  </div>
  <div v-for="ev in eventGroups">
    <p>{{ev.title}}</p>
  </div>
</div>

<script type="text/javascript">
  res = {
    'admin': [
      { 'title': 'event title' },
      { 'title': 'event title' },
      { 'title': 'event title' }
    ],
    'public': [
      { 'title': 'event title' },
      { 'title': 'event title' },
      { 'title': 'event title' }
    ]
  }
</script>

Yo @vue!

You’re almost there. Just move the v-if to the v-for level and change the condition:

<div
  v-for="eventGroups in res"
  v-if="eventGroups.length != 0">
  <div v-for="ev in eventGroups">
    <p>{{ev.title}}</p>
  </div>
</div>
1 Like

Hey sorry - late to the party, this is an old question but I ran into this today here’s a better way that your linter won’t scream at you about (if you use one).

Instead of using v-for and v-if in the same tag, you can use a computed property to filter the array that v-for is using. In the computed property for res, filter out evGroups that are length 0.

Hope this helps!

<div id="app">
  <div v-for="eventGroups in filteredRes">
    <div v-for="ev in eventGroups">
      <p>{{ ev.title }}</p>
    </div>
  </div>
</div>
<script type="text/javascript">
  var app = new Vue({
    el: "#app",
    data: {
      res: {
        'admin': [
          { 'title': 'event title' },
          { 'title': 'event title' },
          { 'title': 'event title' }
        ],
        'public': [
          { 'title': 'event title' },
          { 'title': 'event title' },
          { 'title': 'event title' }
        ]
     }
   },
   computed: {
     filteredRes() {
       return this.res.filter((evGroups) => evGroups.length > 0);
     }
   }
  };
</script>
1 Like