vue3中实现接口轮询
使用 setInterval 实现基础轮询
在 Vue 3 中,可以通过 setInterval 定时调用接口。在组件的 setup 中定义轮询逻辑,注意在组件卸载时清除定时器以避免内存泄漏。
import { onMounted, onUnmounted } from 'vue';
import { fetchData } from './api'; // 替换为实际接口请求方法
export default {
setup() {
let pollInterval;
const pollData = async () => {
try {
const response = await fetchData();
console.log('轮询数据:', response);
} catch (error) {
console.error('轮询失败:', error);
}
};
onMounted(() => {
pollInterval = setInterval(pollData, 5000); // 每5秒轮询一次
});
onUnmounted(() => {
clearInterval(pollInterval);
});
}
};
使用 ref 动态控制轮询间隔
通过 ref 动态调整轮询间隔时间,结合 watch 监听间隔变化并重置定时器。
import { ref, watch, onUnmounted } from 'vue';
export default {
setup() {
const interval = ref(5000); // 默认5秒
let timer = null;
const startPolling = () => {
timer = setInterval(async () => {
console.log('执行轮询...');
}, interval.value);
};
watch(interval, (newVal) => {
clearInterval(timer);
startPolling();
});
onUnmounted(() => clearInterval(timer));
return { interval };
}
};
结合 axios 和错误处理
集成 axios 发送请求,增加错误处理和重试机制。通过 retryCount 限制重试次数。
import axios from 'axios';
import { ref, onUnmounted } from 'vue';
export default {
setup() {
const data = ref(null);
const error = ref(null);
const retryCount = ref(0);
const maxRetries = 3;
let pollInterval;
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com/data');
data.value = response.data;
retryCount.value = 0; // 重置重试计数
} catch (err) {
error.value = err;
if (retryCount.value < maxRetries) {
retryCount.value++;
setTimeout(fetchData, 2000); // 2秒后重试
}
}
};
onMounted(() => {
pollInterval = setInterval(fetchData, 10000); // 每10秒轮询
});
onUnmounted(() => clearInterval(pollInterval));
return { data, error };
}
};
使用自定义 Hook 封装轮询逻辑
将轮询逻辑抽象为可复用的自定义 Hook,提升代码复用性。
// usePolling.js
import { ref, onUnmounted } from 'vue';
export function usePolling(fetchFn, interval = 5000) {
const data = ref(null);
const error = ref(null);
let pollTimer;
const startPolling = () => {
const execute = async () => {
try {
data.value = await fetchFn();
error.value = null;
} catch (err) {
error.value = err;
}
};
execute(); // 立即执行一次
pollTimer = setInterval(execute, interval);
};
const stopPolling = () => {
clearInterval(pollTimer);
};
onUnmounted(stopPolling);
return { data, error, startPolling, stopPolling };
}
在组件中使用自定义 Hook:
import { usePolling } from './usePolling';
import { fetchUser } from './api';
export default {
setup() {
const { data, error } = usePolling(fetchUser, 3000);
return { data, error };
}
};
轮询条件控制
通过条件判断决定是否继续轮询,例如根据接口返回的特定字段终止轮询。
const shouldContinue = ref(true);
const checkStatus = async () => {
const res = await fetchStatus();
if (res.status === 'completed') {
shouldContinue.value = false;
clearInterval(pollInterval);
}
};
const pollInterval = setInterval(() => {
if (shouldContinue.value) checkStatus();
}, 2000);



