当前位置:首页 > 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 动态控制轮询的开启与关闭,增加灵活性。例如,根据业务需求暂停或恢复轮询。

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

vue3中实现接口轮询

标签: 接口
分享给朋友:

相关文章

java如何编写接口

java如何编写接口

编写Java接口的基本语法 在Java中,接口通过interface关键字定义,可以包含抽象方法、默认方法、静态方法和常量。 public interface MyInterface {…

vue实现翻译接口

vue实现翻译接口

使用 Vue 实现翻译接口 安装 Axios 在 Vue 项目中安装 Axios 用于发送 HTTP 请求: npm install axios 配置翻译服务 选择一个翻译 API 服务,例如 G…

vue实现按需调用接口

vue实现按需调用接口

Vue 中按需调用接口的实现方法 在 Vue 项目中按需调用接口可以优化性能,避免不必要的网络请求。以下是几种常见实现方式: 使用计算属性触发接口调用 通过计算属性监听数据变化,在需要时调用接口:…

答辩vue接口如何实现

答辩vue接口如何实现

Vue 接口实现的核心方法 使用 Axios 或 Fetch 发起 HTTP 请求 Axios 是 Vue 项目中常用的 HTTP 客户端,需先通过 npm install axios 安装。在组件中…

Vue调接口怎么实现

Vue调接口怎么实现

Vue调用接口的实现方法 在Vue中调用接口通常使用axios或fetch等HTTP客户端库,以下是具体实现方式: 安装axios 通过npm或yarn安装axios依赖: npm install…

react如何接接口

react如何接接口

React 中接入接口的常见方法 使用 fetch API 发起 HTTP 请求fetch 是浏览器原生支持的 API,无需额外安装库。发起 GET 请求的示例代码如下: fetch('https:…