定时刷新列表并自主实现转圈加载Loading

996 阅读2分钟

应用场景:在实现一个任务列表的时候,有启动按钮、停止按钮、中断按钮,点击启动按钮之后,后台启动任务需要一定的时间,当立即刷新启动按钮时,任务状态仍然是完成状态。

实现思路:

  • 在点击启动之后,立即刷新列表,后台将该任务状态置为正在启动的状态标识;
  • 前端将任务状态置为正在启动,并加上动态loading;
  • 这时候写定时任务定时刷新列表,直到列表内没有正在启动的状态标识,清除定时器。 实现后的效果图如下:

任务未启动时

点击启动按钮后

动态loading

@keyframes cirAnimate {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}
.cir:before {
  content: '';
  position: absolute;
  left: 18px;
  top: 3px;
  height: 14px;
  width: 14px;
  z-index: 1000;
  border: 2px solid;
  border-radius: 50%;
  border-color: #2196f324 #03a9f4 #03a9f4 #03a9f4;
  animation: cirAnimate 1.5s linear infinite;
}

jobStatus===1 判断任务是不是正在启动的状态,是则显示正在启动,并且加上动态loading的class。

<div
  v-if="scope.row.jobStatus === 1"
  :class="{ cir: scope.row.jobStatus === 1 }"
>
  <span style="margin-left:25px">正在启动</span>
</div>

定时任务

reloadPage() {
      const that = this;
      // 清除之前定时器
      clearInterval(this.timer);
      this.timer = setInterval(function() {
        that.getTaskList(that.projectId).then(res => {
          // 如果tableData即任务列表,没有正在启动的任务,则清除定时器
          const arrStart = that.tableData.filter(item => {
            return item.jobStatus === 1;
          });
          if (arrStart.length === 0) {
            clearInterval(that.timer);
          }
        });
      }, 6000);
    },

写好定时器,需要判断当前任务列表是否需要启动定时任务

判断原因:如果用户点击了启动,但任务未启动完成,用户切换到其他页面或者直接刷新页面,这时候需要判断是否开启定时任务,如果不判断,用户不切换界面,则任务会一直处于正在启动状态。

判断函数:

// 调用任务列表,查看是否存在jobStatus为1,是则定时刷新
    isReloadPage(id) {
      this.getTaskList(id).then(res => {
        for (let i = 0, arrLength = this.tableData.length; i < arrLength; i++) {
          if (this.tableData[i].jobStatus === 1) {
            this.reloadPage();
            break;
          }
        }
      });
    },