【发布时间】:2020-01-05 13:13:23
【问题描述】:
场景如下……
组件模板
<template>
<div>
<loader v-show="loading"></loader> // 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>
组件数据
data: function () {
return {
list: [],
groups: [],
loading: true
}
}
1.从 api 获取一维数组
axios.get(API_URL).then(
(response) => {
this.list = response.data.payload;
}
);
数组结构如下...
[
{
"name": "bob",
"group": "A"
},
{
"name": "sally",
"group": "A"
},
{
"name": "john",
"group": "B"
},
{
"name": "jane",
"group": "B"
},
]
2。使用每个项目的 group 属性将数组转换为二维
当前解决方案(阻塞!,效率低下?)
// loading animation stops at this point
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;
在填充组之前如何保持加载动画?
【问题讨论】:
-
您想要一种有效地填充数组的方法,还是要确保加载动画在您加载数据之前一直运行?您当前的解决方案是否使加载动画持续到最后?是什么让您当前的解决方案受阻?
标签: javascript arrays vue.js async-await