Overview
This example is useful if you want to show a unique header only once in your v-for list.
For instance, if you had an array of objects:
"procedures": [{
"category": "Lips",
"procedure": "Fat Burner"
}, {
"category": "Botulinum Toxin",
"procedure": "1 Area"
}, {
"category": "Botulinum Toxin",
"procedure": "2 Areas"
}, {
"category": "Botulinum Toxin",
"procedure": "3 Areas"
}, {
"category": "Dermal Filler",
"procedure": "Chin"
}, {
"category": "Dermal Filler",
"procedure": "Nasolabial"}]
and you wanted to have unique headers for each category such as:
Solution
This solution requires some JavaScript to work.
I thought about nesting v-for loops, but needed a new array with unique categories for my outer loop.
I utilized a lodash function called _.uniqWith to only grab the unique categories.
In my onFormLoad:
var result = _.uniqWith(model.procedures, function(arrVal, othVal) {
return arrVal.category === othVal.category;
});
model.uniqCat = result
Remember to instantiate uniqCat in your data model
v-for
Now that we have our new array, we can use v-for to loop through each category, and then an additional v-for to loop through each procedure in that category.
<div v-for="header in model.uniqCat">
{{header.category}}
<div v-for="line in model.procedures" v-if="line.category == header.category">
{{line.procedure}}
</div>
</div>
My outer loop loops through each category, and my inner loop loops through each procedure. It has a v-if to check if the procedure matches the header category of the outer loop so that every procedure doesn’t get rendered 3 times.
This will end up looking like:
With some additional styling:
<div v-for="header in model.uniqCat">
<div class="bg-blue-100 text-black font-bold">{{header.category}}</div>
<div v-for="(line, index) in model.procedures"
v-if="line.category == header.category"
class="ml-8 h-8 align-middle text-black font-semibold"
:class="index % 2 == 0 ? 'bg-gray-50' : ''">
{{line.procedure}}
<button class="btn bg-sky-700 text-white p-1 pull-right mb-0">Delete</button>
</div>
</div>
We can get pretty close to our desired result:
Conclusion
Because of the nested loop, I wonder if there may be performance issues if the array is large. There may be other solutions rather than creating a new array, however I found this to be relatively simple. Hope this helps!