vuejs2 - vue.js如何在处理数据时显示进度
问题描述
我在 vue.js 中有一个页面构建,其中调用了一个 API(使用 axios)获取一个大的 json 对象(1k+)。
当我处理这个对象时,我想向用户展示操作的进度——没有什么比进度条更花哨的了,只是一个简单的“从 Y 处理的 X”。
我已经找到了如何在纯 JS 的 jquery 中执行此操作的示例,但我可以让它在 vue 中工作。
任何帮助表示赞赏。
这是我的骨架代码:
<div>Processed {{processed.current}} of {{processed.total}} records</div>
<script>
data() {
return {
progress:{
current:0,
total: 0
},
records: [],
};
},
mounted() {
this.getRecords();
},
methods: {
getRecords(){
axios({
method: "GET",
url: process.env.VUE_APP_REPORTING_API + "/Reports/orders",
headers: {
"content-type": "application/json",
Authorization: this.$cookie.get("wwa_token")
}
}).then(
result => {
this.progress.total = result.data.length;
//and here where the loop should happen, something like this
//obviously the below won't work :)
result.data.forEach(function(item) {
this.records.push(item);
this.progress.current++;
}
},
error => {
}
);
}
}
</script>
解决方案
好吧,发布代码的一个明显问题是它有一个语法错误(缺少右括号)并且它建立了一个新的上下文。如果将代码更改为使用箭头函数,该代码将(有点)“工作”:
result.data.forEach(item => {
this.records.push(item);
this.progress.current++;
});
但是,我认为这不会做你想要的。JavaScript 代码将在用户界面更新之前处理所有项目,因此用户将看到的所有内容将是“已处理 N 条记录”。即使您this.$forceUpdate()
在循环中插入 a 以在每次迭代时更新界面,更改仍然太快,任何用户都无法看到。
真正的问题是“处理”所有项目只需要几毫秒。所以它总是会发生得太快而无法显示中间结果。
如果您试图显示 AJAX 请求/响应的进度,这是一个完全不同的问题,需要客户端和服务器之间的协调。搜索 HTTP 分块响应作为开始。
推荐阅读
- excel - 如果我关于 Metabase 的问题有一个带有图像预览的图像列,是否可以将其作为图像类型列本身导出到 excel 中?
- shell - 如何在 GNU Make 中使用 shell 命令来回显字符串
- c++ - C++ 中 std::iota 的效率?
- google-kubernetes-engine - 将我的 GKE 集群连接到本地数据库
- c++ - 递归模板调用中无法调用模板化函数重载
- python - 在将字符串绘制为图像时获取每个字符的边界框信息
- cypher - 无法在 gremlin 中使用密码创建索引
- node.js - GCP:应用服务版本的配置
- cesium - 如何在铯中定义tileset位置
- rust - 为什么 FlatBufferBuilder 有生命周期?