Search code examples
javascriptvue.jsvuejs3v-for

V-for with v-if or computed property


I've been having issue with understanding computed properties, but I think that's what I need with my issue.Basically, I have a table, with columns I populate from API response. One of those columns is Monthly, where I need to check current month and year, and then write left usage for that month. In case I don't have data for month or year, or the array is empty, I should break that loop, and show main_usage.

I was thinking about using computed property, but I'm not sure how..

There's sample code and json below

<!-- First v-for for looping through all permissions data -->    

 <tr v-for="t in permissions" :key="t.id">    

<!-- If we have data in .permission_usage show it -->    

<template v-if="t.permission_usage.length">    

<!-- Loop through permission_usage -->      

<template v-for="p in t.permission_usage" :key="p.id">
<!--Check dates, works fine -->      

 <template v-if="currentYear()===p.year && currentMonth()===p.month">    

<!-- Shows data as it should -->      

 <td>{{p.used}}</td>      
</template>

<!-- Here comes my issue -->      

 <template v-else>    

<!-- I don't want to loop through data anymore, because I would have main_usage for every permission_usage because i'm in loop, here I would like to break loop-->      

 <td>{{t.main_usage}}</td>      
</template>

 </template>      
</template>

<!-- If we don't have data in .permission_usage show main_usage -->      

 <template v-else>      
<td>{{t.main_usage}}</td> </template>

</tr>  

//response is stored in perimissions array

//currentMonth() and currentYear() return value of current month and current year

JSON

[
{
"main_usage": 5000,
"permission_usage": [
{
"year": 2021,
"month": 6,
"used": 66,
},
{
"year": 2021,
"month": 7,
"used": 220,
},
....
]
},
...
]

Here's the fiddle https://jsfiddle.net/2bk4ga5y/57/ , but my output should be:

220

77

33

1500.

Thanks in advance!


Solution

  • So I come to understanding that I can't change things directly in UI, and that I need to play around with data BEFORE it renders on the page, and when I realised that, it was really easy. So, in that method, I made a new property called showRenderedData with value of string "None" and binded it to my template, so it would always show "None". Then, I made first forEach looping through permissions, and there I override my new property showRenderData to main_usage. After that loop, I made another forEach for looping through permission_usage, made condition there to check months and length, and only if the conditions were met I would override where the conditions were met with property with row_export_usage. I will edit fiddle later with this method so someone can see it in action.