vue页面设置定时请求数据

134 阅读1分钟

当某个页面或者组件需要实现重复请求数据,需要使用到定时器来设置重复请求 代码实现

// 在mounted生命周期中执行定时器函数
mounted() {
  // 初始化时第一次执行
  this.getData()
  // 定时执行
  this.startPolling();
},
 
 // 离开页面时销毁定时器
 destroyed() {
    // 组件销毁时清除定时器
    clearInterval(this.refreshTimer)
 },
 
 methods: {
   //请求数据函数
   getData() {
     // 封装的api请求
     getApi(this.queryParams).then((response) => {
       // 执行请求到数据后的逻辑...
       // ...
     });
  },
    
    // 定时器函数
startPolling() {
  // 设置定时器
  const interval = 10000; // 定时刷新间隔,例如 10 秒
  this.refreshTimer = setInterval(() => {
  // 时间到后执行的方法
  this.getData();
    }, interval);
  },
}

如果页面使用了keep-alive组件的话,需要在keep-alive特有的生命周期中执行一下两个生命周期,销毁定时器和重新开始定时器

activated() {
  console.log('--->重新开始定时器');
  this.setRefreshTimer();
},
 
deactivated() {
  console.log('--->清除定时器');
  this.clearRefreshTimer();
},