clone45
clone45

Reputation: 9040

Vue.js: Checking if a v-for loop that uses a v-if conditional rendered any items?

If I have the following code:

<template v-for="(item, index) in items" v-if="item.name === 'foo'">
   <p>{{ item.name }}</p>
</template>

How would I print out a message if this loop outputs nothing?

Thanks!

Upvotes: 2

Views: 758

Answers (1)

Phil
Phil

Reputation: 164910

I'd use a computed property to create the filtered list. Then you can use a v-if based on the list length. For example

computed: {
  fooItems () {
    return this.items.filter(({name}) => name === 'foo')
  }
}

and in your template

<template v-for="(item, index) in fooItems">
  <p>{{ item.name }}</p>
</template>
<p v-if="fooItems.length === 0">
  Nothing to show
</p>

Upvotes: 4

Related Questions