Let's dive into the scenario...
Here is the template for our component
<template>
<div>
<loader v-show="loading"></loader> // display loading animation
<div v-show="!loading">
<div v-for="group in groups">
{{group.name}}
<div v-for="item in group.list">
{{item.name}}
</div>
</div>
</div>
</div>
</template>
Now, let's look at the data for our component
data: function () {
return {
list: [],
groups: [],
loading: true
}
}
1. Fetch a one-dimensional array from an API
axios.get(API_URL).then(
(response) => {
this.list = response.data.payload;
}
);
The structure of the array is as follows...
[
{
"name": "bob",
"group": "A"
},
{
"name": "sally",
"group": "A"
},
{
"name": "john",
"group": "B"
},
{
"name": "jane",
"group": "B"
},
]
2. Transform the array into two dimensions based on the 'group' property
Current solution (blocking!, inefficient?)
// loading animation stops here
this.list.forEach((item, index) => {
let hasGroupChanged = false;
if (index === 0) {
hasGroupChanged = true;
} else {
let currentGroupName = item.group;
let previousGroupName = this.list[index - 1].group;
hasGroupChanged = previousGroupName !== currentGroupName;
}
if (hasGroupChanged) {
const group = {
group: item.group,
list: []
};
this.groups.push(group);
}
const groupIndex = this.groups.length - 1;
this.groups[groupIndex].list.push(item);
});
this.loading = false;
How can we ensure that the loading animation continues until the groups are fully populated?