Aishwerya
Aishwerya

Reputation: 99

Get items with conditional rendering based on their type

There's List in which data in segregated based on their particular type

Task to accomplish :- display the only items of desired type.

<script>
export default {
  data(){
    return{
    items:{
        {
          type: "a",
          text: "TEXT A"
        },
        {
          type: "b",
          text: "TEXT B"
        },
        {
          type: "b",
          text: "TEXT B-1"
        },{
          type: "a",
          text: "TEXT A-2"
        }
      }
    }
  }
  </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
  <div v-if="type == a">
    <div v-for="(item,key) in items">
      <p>{{item.text}}</p>
    </div>
  </div>
</template>

Upvotes: 0

Views: 28

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You should put a conditional rendering inside the v-for loop like :

<div >
  <div v-for="(item,key) in items">
  <p v-if="item.type == 'a'">{{item.text}}</p>
  </div>
</div>

or use a computed property called itemsTypeA and return only that items which their type == a and loop through that property inside your template :

   computed:{
          itemsTypeA(){
              return this.items.filter(item=>{
              return item.type=='a'
              })
            }
        }

inside the template :

 <div >
  <div v-for="(item,key) in itemsTypeA">
  <p>{{item.text}}</p>
  </div>
</div>

Upvotes: 1

Related Questions