Count total of v-if output in v-for

Viewed 105

I have a code like

<template>
  <div v-for="(item, i) in items" :key="i">
    <div v-for="(subitem, index) in subitems" :key="index" v- 
       if="item.id==subitem.item_id">
    {{count(subitem)}}
    </div>
  </div>
</template>
<script>
data() {
  return {
    items: [],
    subitems: [],
  }
}

watch: {

  items : async function() {
  const itm = await('get','/item')
  this.items = itm
    },

  subitems : async function() {
  const subitm = await('get','/sub_items')
  this.subitems = subitm

    },
},
</script>

The items and subitems array get the values of array from the api fetch in watch property. There is item id in each subitems values, Now I want count or length of for each v if output of subitem which is equal to item id. How to do that?

Thank you

1 Answers

You can't put v-for and v-if on the same element can you please provide more about your array structure so i can give you the best way but from what i have you can create do this function after getting item and subitem

items.foreach((element)=>{
element.subitemCount=0;
subitem.foreach(item=>{
if(element.id==item.item_id){
element.subitemCount++;}}

And for your vuejs you can write this

<div v-for="(item, i) in items" :key="i">  {{item.subitemCount}} </div>
Related