当前位置:首页 > 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 实现接口调用

使用 Axios 进行接口调用 安装 Axios 依赖: npm install axios 在 Vue 组件中引入并使用: import axios from 'axios'; export…

vue实现接口配置

vue实现接口配置

Vue 中实现接口配置的方法 在 Vue 项目中配置接口通常涉及以下几个关键步骤: 创建 API 配置文件 新建一个 api 目录,创建 index.js 文件作为接口配置入口。可以将接口按模块分类…

react如何接接口

react如何接接口

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

react如何访问本地接口

react如何访问本地接口

访问本地接口的方法 在React中访问本地接口通常涉及开发环境配置和跨域问题处理。本地接口可能运行在本地开发服务器(如localhost:3000)或其他端口(如后端服务的localhost:8080…

php实现接口方法

php实现接口方法

PHP 实现接口方法 在 PHP 中,接口(Interface)用于定义一组方法的规范,类通过实现接口来遵循这些规范。以下是实现接口方法的具体步骤和示例: 定义接口 接口通过 interface 关…

php接口实现

php接口实现

PHP接口实现方法 定义接口 使用interface关键字定义接口,接口中只能包含抽象方法和常量。接口方法必须是公开的,且不包含具体实现。 interface LoggerInterface {…