Vue项目中重复调用接口

271 阅读1分钟

背景

这一段时间项目中有个需求,在这个页面需要使用定时器调用接口。实时看数据状态的改变。话不多说上代码。

<script>
export default{
 data(){
 return{
 timer:null.
},
methods:{
     async builds(){
       let {code} = await mastBuild({branchId:this.branchId});
       if(code == 200) {
          this.$message({
          message: '操作成功',
          type: 'success'
        });
       }else{
        this.$message.error('流水线正在执行中');
       }
       this.timer = setInterval(async () => {
         // 给 timer变量赋值为 定时器 方便清除定时器 这里设置的五秒请求一次
         this.getNewBuild(); // 需要重复调用的接口
       }, 5000);
    },
       // 重新获取 table 里的数据
    async getNewBuilds(){
      let params = {
        pageNum: 0,
        pageSize: 10,
        branchId: this.branchId
      }
      let { content,total } = await getHistorys(params)//后端接口
      this.tables = content;
      this.total = total;
      if(this.tables[0]?.states != 1// 根据返回的数据来判断是否清除定时器
          clearInterval(this.timer);
      }
    },
}

</script>

在项目中使用定时器不是很难的知识点,就是想记录下。哈哈哈哈哈