首页 > 解决方案 > 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>

标签: vuejs2

解决方案


好吧,发布代码的一个明显问题是它有一个语法错误(缺少右括号)并且它建立了一个新的上下文。如果将代码更改为使用箭头函数,该代码将(有点)“工作”:

result.data.forEach(item => {
    this.records.push(item);
    this.progress.current++;
});

但是,我认为这不会做你想要的。JavaScript 代码将在用户界面更新之前处理所有项目,因此用户将看到的所有内容将是“已处理 N 条记录”。即使您this.$forceUpdate()在循环中插入 a 以在每次迭代时更新界面,更改仍然太快,任何用户都无法看到。

真正的问题是“处理”所有项目只需要几毫秒。所以它总是会发生得太快而无法显示中间结果。

如果您试图显示 AJAX 请求/响应的进度,这是一个完全不同的问题,需要客户端和服务器之间的协调。搜索 HTTP 分块响应作为开始。


推荐阅读