Home » vue » Vue loop using v-for then display only if no condition met

Vue loop using v-for then display only if no condition met

Posted by: admin November 26, 2021 Leave a comment

Questions:

I am having hard time displaying a specific message if while using v-for the condition is not met I want to display a specific message.
In my case an product status can be ‘processing’, ‘delivered’ or ‘completed’
While using v-for for products which are ‘processing’ I want to display an message example: No product

The problem in my case is that if I have 2 products then I get the message 2 time displayed..

This is my code so far:

<template>
  <div class="">
    <template v-for="(product, index) in products">
      <v-layout row wrap v-if="product.status === 'processing'">
        processing products here
      </v-layout>
      <v-layout>
        There is not product being processed
      </v-layout>
    </template>

  </div>
</template>
<script>

import { mapGetters } from 'vuex'

export default {
  name: 'productPage',
  data () {
    return {
      products: [
        {
          status: 'processing',
          name: 'Product processing'
        },
        {
          status: 'delivered',
          name: 'Product delivered'
        }
      ]
    }
  },
  computed: {
    ...mapGetters({
      filter: 'main/filter'
    })
  }
}
</script>

How should I do this in my case? And show the message only if no condition is met. I also tried to play around with v-once but I couldn’t make it..

Answers:

I would make a computed property named isProcessing:

  • Return true if there’s at least one product is being processed.
  • Return false otherwise.

In the template, use v-if='isProcessing' to show There is not product being processed and v-else to show list of products which are being processed.

computed: {
    isProcessing: function () {
        return this.products.find( product => product.status === 'processing' ) !== undefined
    }
}