当前位置:首页 > VUE

vue3中实现接口轮询

2026-01-12 08:06:31VUE

使用 setInterval 实现基础轮询

在 Vue 3 中,可以通过 setInterval 定时调用接口。在组件的 onMounted 钩子中启动轮询,并在 onUnmounted 钩子中清除定时器以避免内存泄漏。

import { onMounted, onUnmounted } from 'vue';
import { fetchData } from './api';

let pollInterval;

onMounted(() => {
  pollInterval = setInterval(async () => {
    try {
      const data = await fetchData();
      console.log('轮询数据:', data);
    } catch (error) {
      console.error('轮询失败:', error);
    }
  }, 5000); // 每5秒轮询一次
});

onUnmounted(() => {
  clearInterval(pollInterval);
});

使用 ref 管理轮询状态

通过 ref 动态控制轮询的开启与关闭,增加灵活性。例如,根据业务需求暂停或恢复轮询。

vue3中实现接口轮询

import { ref, onMounted, onUnmounted } from 'vue';
import { fetchData } from './api';

const isPolling = ref(true);
let pollInterval;

const startPolling = () => {
  pollInterval = setInterval(async () => {
    if (!isPolling.value) return;
    try {
      const data = await fetchData();
      console.log('轮询数据:', data);
    } catch (error) {
      console.error('轮询失败:', error);
    }
  }, 5000);
};

onMounted(startPolling);
onUnmounted(() => clearInterval(pollInterval));

// 暂停轮询
const pausePolling = () => {
  isPolling.value = false;
};

// 恢复轮询
const resumePolling = () => {
  isPolling.value = true;
};

结合 watch 实现条件轮询

当轮询依赖某些响应式变量时,可以通过 watch 监听变化并动态调整轮询逻辑。例如,根据页面可见性决定是否继续轮询。

vue3中实现接口轮询

import { ref, watch, onMounted, onUnmounted } from 'vue';
import { fetchData } from './api';

const isPageVisible = ref(true);
let pollInterval;

const startPolling = () => {
  pollInterval = setInterval(async () => {
    if (!isPageVisible.value) return;
    try {
      const data = await fetchData();
      console.log('轮询数据:', data);
    } catch (error) {
      console.error('轮询失败:', error);
    }
  }, 5000);
};

watch(isPageVisible, (visible) => {
  if (visible) startPolling();
  else clearInterval(pollInterval);
});

onMounted(startPolling);
onUnmounted(() => clearInterval(pollInterval));

使用 axios 拦截器处理错误

在轮询中,接口可能因网络问题失败。通过 axios 拦截器统一处理错误,避免轮询中断。

import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.example.com',
});

api.interceptors.response.use(
  (response) => response.data,
  (error) => {
    console.error('请求失败:', error);
    return Promise.reject(error);
  }
);

// 轮询逻辑中直接调用封装后的接口
const fetchData = () => api.get('/data');

指数退避策略优化轮询

在网络不稳定时,采用指数退避策略动态调整轮询间隔,减少无效请求。

let retryCount = 0;
const MAX_RETRY_DELAY = 30000; // 最大延迟30秒

const fetchWithRetry = async () => {
  try {
    const data = await fetchData();
    retryCount = 0; // 成功时重置重试计数
    console.log('轮询数据:', data);
  } catch (error) {
    retryCount++;
    const delay = Math.min(1000 * 2  retryCount, MAX_RETRY_DELAY);
    console.log(`请求失败,${delay / 1000}秒后重试`);
    setTimeout(fetchWithRetry, delay);
  }
};

onMounted(() => {
  fetchWithRetry(); // 启动首次请求
});

标签: 接口
分享给朋友:

相关文章

vue实现接口轮询

vue实现接口轮询

实现接口轮询的基本方法 在Vue中实现接口轮询通常通过setInterval或setTimeout结合异步请求完成。以下是一个基础实现示例: data() { return { pol…

vue实现接口连接

vue实现接口连接

Vue 实现接口连接的常用方法 Vue 中实现接口连接通常需要借助 HTTP 客户端库,以下是几种常见实现方式: 使用 Axios Axios 是流行的 HTTP 客户端库,支持 Promise A…

vue实现接口地图

vue实现接口地图

Vue 中实现接口地图(基于第三方地图服务) 以高德地图为例,展示如何在 Vue 项目中集成地图服务并调用接口实现功能。 安装高德地图 SDK 在项目中引入高德地图 JavaScript API,…