vue3中实现接口轮询
使用 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 动态控制轮询的开启与关闭,增加灵活性。例如,根据业务需求暂停或恢复轮询。

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 监听变化并动态调整轮询逻辑。例如,根据页面可见性决定是否继续轮询。

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(); // 启动首次请求
});



